Ejemplo n.º 1
0
def main():
    '''Parses command line arguments and config file to generate detector file'''
    logging.basicConfig(filename="recon.log", level=logging.INFO,
                        format='%(asctime)s - %(levelname)s - %(message)s')
    parser = py_utils.MyArgparser(description="make detector")
    args = parser.special_parse_args()

    det_file = os.path.join(args.main_dir,
                            read_config.get_filename(args.config_file,
                                                     'make_detector',
                                                     'out_detector_file'))
    if args.yes:
        to_write = True
    else:
        to_write = py_utils.check_to_overwrite(det_file)
    logging.info("\n\nStarting make_detector....")
    logging.info(' '.join(sys.argv))

    if to_write:
        timer = py_utils.MyTimer()
        pm = read_config.get_detector_config(args.config_file, show=args.vb) # pylint: disable=C0103
        q_pm = read_config.compute_q_params(pm['detd'], pm['dets_x'],
                                            pm['dets_y'], pm['pixsize'],
                                            pm['wavelength'], pm['ewald_rad'], show=args.vb)
        timer.reset_and_report("Reading experiment parameters") if args.vb else timer.reset()

        qscaling = 1. / pm['wavelength'] / q_pm['q_sep']
        (x, y) = np.mgrid[0:pm['dets_x'], 0:pm['dets_y']]
        (x, y) = (x.flatten()-pm['detc_x'], y.flatten()-pm['detc_y'])
        norm = np.sqrt(x**2 + y**2 + (pm['detd']/pm['pixsize'])**2)
        polar = read_config.compute_polarization(pm['polarization'], x, y, norm)
        (qx, qy, qz) = (x*qscaling/norm, # pylint: disable=C0103
                        y*qscaling/norm,
                        qscaling*(pm['detd']/pm['pixsize']/norm - 1.))
        logging.info('%15s:%10.4f', 'qmax', np.sqrt(qx*qx + qy*qy + qz*qz).max())
        solid_angle = pm['detd'] / pm['pixsize'] / norm**3
        solid_angle = polar*solid_angle
        rad = np.sqrt(x*x + y*y)
        if pm['mask_fname'] is None:
            mask = np.zeros(solid_angle.shape, dtype='u1')
            mask[rad > min(pm['detc_x'], pm['detc_y'])] = 1
            mask[rad < pm['stoprad']] = 2
        else:
            mask = np.fromfile(pm['mask_fname'], '=u1')
            mask[(rad > min(pm['detc_x'], pm['detc_y'])) & (mask == 0)] = 1
        timer.reset_and_report("Creating detector") if args.vb else timer.reset()

        with open(det_file, "w") as fptr:
            #fptr.write(str(pm['dets_x']*pm['dets_y']) + "\n")
            fptr.write("%d %.6f %.6f\n" % (pm['dets_x']*pm['dets_y'],
                                           pm['detd']/pm['pixsize'],
                                           pm['ewald_rad']))
            for par0, par1, par2, par3, par4 in zip(qx, qy, qz, solid_angle, mask):
                txt = "%21.15e %21.15e %21.15e %21.15e %d\n"%(par0, par1, par2, par3, par4)
                fptr.write(txt)
        timer.reset_and_report("Writing detector") if args.vb else timer.reset()

        timer.report_time_since_beginning() if args.vb else timer.reset()
    else:
        pass
Ejemplo n.º 2
0
    args = parser.special_parse_args()

    logging.info('Starting cheetahtodet...')
    logging.info(' '.join(sys.argv))
    pm = read_config.get_detector_config(args.config_file, show=args.vb)
    q_pm = read_config.compute_q_params(pm['detd'], pm['dets_x'], pm['dets_y'], pm['pixsize'], pm['wavelength'], pm['ewald_rad'], show=args.vb)
    output_folder = read_config.get_filename(args.config_file, 'emc', 'output_folder')

    # Cheetah geometry files have coordinates in m
    with h5py.File(args.h5_name, 'r') as f:
        x = f['x'][:].flatten() * 1.e3
        y = f['y'][:].flatten() * 1.e3
        z = f['z'][:].flatten() * 1.e3 + pm['detd']
    
    norm = np.sqrt(x*x + y*y + z*z)
    polar = read_config.compute_polarization(pm['polarization'], x, y, norm)
    qscaling    = 1. / pm['wavelength'] / q_pm['q_sep']
    qx = x * qscaling / norm
    qy = y * qscaling / norm
    qz = qscaling * (z / norm - 1.)
    solid_angle = pm['detd']*(pm['pixsize']*pm['pixsize']) / np.power(norm, 3.0)
    solid_angle = polar*solid_angle
    radius = np.sqrt(x*x + y*y)
    if args.mask is None:
        rmax = min(np.abs(x.max()), np.abs(x.min()), np.abs(y.max()), np.abs(y.min()))
        mask = np.zeros(solid_angle.shape, dtype='u1')
        mask[radius>rmax] = 1
    else:
        with h5py.File(args.mask, 'r') as f:
            mask = f[args.mask_dset][:].astype('u1').flatten()
    
Ejemplo n.º 3
0
    q_pm = read_config.compute_q_params(pm['detd'], pm['dets_x'], pm['dets_y'], pm['pixsize'], pm['wavelength'], pm['ewald_rad'], show=args.vb)
    output_folder = read_config.get_filename(args.config_file, 'emc', 'output_folder')

    ds = psana.DataSource(args.exp_string + ':idx')
    run = ds.runs().next()
    times = run.times()
    evt = run.event(times[0])
    det = psana.Detector(args.det_name)
    cx = det.coords_x(evt).flatten() * 1.e-3
    cy = det.coords_y(evt).flatten() * 1.e-3

    detd = pm['detd']
    qscaling = 1. / pm['wavelength'] / q_pm['q_sep']
    rad = np.sqrt(cx*cx + cy*cy)
    norm = np.sqrt(cx*cx + cy*cy + detd*detd)
    polar = read_config.compute_polarization(pm['polarization'], cx, cy, norm)
    qx = cx * qscaling / norm
    qy = cy * qscaling / norm
    qz = qscaling * (detd / norm - 1.)
    solid_angle = pm['detd']*pm['pixsize']*pm['pixsize'] / np.power(norm, 3.0)
    solid_angle = polar*solid_angle

    if pm['mask_fname'] is None:
        mask = det.mask(evt, status=True, calib=True, edges=True, central=True, unbondnbrs8=True).flatten()
        mask = 2*(1 - mask)
        rmax = min(cx.max(), np.abs(cx.min()), cy.max(), np.abs(cy.min()))
        mask[(rad>rmax) & (mask==0)] = 1
    else:
        mask = np.fromfile(pm['mask_fname'], '=u1')

    det_file = output_folder + '/det_' + args.exp_string.split(':')[0][4:] + '.dat'
Ejemplo n.º 4
0
def main():
    """Parse command line arguments and generate file"""
    logging.basicConfig(filename='recon.log',
                        level=logging.INFO,
                        format='%(asctime)s - %(levelname)s - %(message)s')
    parser = py_utils.MyArgparser(description='PSANA to det')
    parser.add_argument('exp_string', help='PSANA experiment string')
    parser.add_argument(
        'det_name', help='PSANA Detector name (either source string or alias)')
    parser.add_argument(
        '-C',
        '--corners',
        help='Set corner pixels to be irrelevant. Default = False',
        action='store_true',
        default=False)
    args = parser.special_parse_args()

    logging.info('Starting psanatodet...')
    logging.info(' '.join(sys.argv))
    pm = read_config.get_detector_config(args.config_file, show=args.vb)  # pylint: disable=invalid-name
    q_pm = read_config.compute_q_params(pm['detd'],
                                        pm['dets_x'],
                                        pm['dets_y'],
                                        pm['pixsize'],
                                        pm['wavelength'],
                                        pm['ewald_rad'],
                                        show=args.vb)
    output_folder = read_config.get_filename(args.config_file, 'emc',
                                             'output_folder')

    dsource = psana.DataSource(args.exp_string + ':idx')
    run = dsource.runs().next()
    times = run.times()
    evt = run.event(times[0])
    psana_det = psana.Detector(args.det_name)
    cx = psana_det.coords_x(evt).flatten() * 1.e-3  # pylint: disable=invalid-name
    cy = psana_det.coords_y(evt).flatten() * 1.e-3  # pylint: disable=invalid-name

    detd = pm['detd']  # in mm
    qscaling = 1. / pm['wavelength'] / q_pm['q_sep']
    rad = np.sqrt(cx * cx + cy * cy)
    norm = np.sqrt(cx * cx + cy * cy + detd * detd)
    polar = read_config.compute_polarization(pm['polarization'], cx, cy, norm)

    det = detector.Detector()
    det.detd = detd / pm['pixsize']
    det.ewald_rad = pm['ewald_rad']
    det.qx = cx * qscaling / norm
    det.qy = cy * qscaling / norm
    det.qz = qscaling * (detd / norm - 1.)
    det.corr = pm['detd'] * pm['pixsize'] * pm['pixsize'] / np.power(norm, 3.0)
    det.corr *= polar

    if pm['mask_fname'] is None:
        det.raw_mask = psana_det.mask(evt,
                                      status=True,
                                      calib=True,
                                      edges=True,
                                      central=True,
                                      unbondnbrs8=True).flatten()
        det.raw_mask = 2 * (1 - det.raw_mask)
        if args.corners:
            rmax = min(cx.max(), np.abs(cx.min()), cy.max(), np.abs(cy.min()))
            det.raw_mask[(rad > rmax) & (det.raw_mask == 0)] = 1
    else:
        det.raw_mask = np.fromfile(pm['mask_fname'], '=u1')

    det_file = output_folder + '/det_' + args.exp_string.split(':')[0][4:]
    try:
        import h5py
        det_file += '.h5'
    except ImportError:
        det_file += '.dat'
    sys.stderr.write('Writing detector file to %s\n' % det_file)
    det.write(det_file)
Ejemplo n.º 5
0
def main():
    """Parse command line arguments and convert file"""
    logging.basicConfig(filename='recon.log',
                        level=logging.INFO,
                        format='%(asctime)s - %(levelname)s - %(message)s')
    parser = py_utils.MyArgparser(description='cheetahtodet')
    parser.add_argument('h5_name',
                        help='HDF5 file to convert to detector format')
    parser.add_argument(
        '-M',
        '--mask',
        help=
        'Path to detector style mask (0:good, 1:no_orient, 2:bad) in h5 file')
    parser.add_argument('--mask_dset',
                        help='Data set in mask file. Default: /data/data',
                        default='data/data')
    parser.add_argument(
        '--dragonfly_mask',
        help='Whether mask has Dragonfly style values or not. (Default: false)',
        default=False,
        action='store_true')
    args = parser.special_parse_args()

    logging.info('Starting cheetahtodet...')
    logging.info(' '.join(sys.argv))
    pm = read_config.get_detector_config(args.config_file, show=args.vb)  # pylint: disable=invalid-name
    q_pm = read_config.compute_q_params(pm['detd'],
                                        pm['dets_x'],
                                        pm['dets_y'],
                                        pm['pixsize'],
                                        pm['wavelength'],
                                        pm['ewald_rad'],
                                        show=args.vb)
    output_folder = read_config.get_filename(args.config_file, 'emc',
                                             'output_folder')

    # Cheetah geometry files have coordinates in m
    with h5py.File(args.h5_name, 'r') as fptr:
        x = fptr['x'][:].flatten() * 1.e3
        y = fptr['y'][:].flatten() * 1.e3
        z = fptr['z'][:].flatten() * 1.e3 + pm['detd']

    det = detector.Detector()
    norm = np.sqrt(x * x + y * y + z * z)
    qscaling = 1. / pm['wavelength'] / q_pm['q_sep']
    det.qx = x * qscaling / norm
    det.qy = y * qscaling / norm
    det.qz = qscaling * (z / norm - 1.)
    det.corr = pm['detd'] * (pm['pixsize'] * pm['pixsize']) / np.power(
        norm, 3.0)
    det.corr *= read_config.compute_polarization(pm['polarization'], x, y,
                                                 norm)
    if args.mask is None:
        radius = np.sqrt(x * x + y * y)
        rmax = min(np.abs(x.max()), np.abs(x.min()), np.abs(y.max()),
                   np.abs(y.min()))
        det.raw_mask = np.zeros(det.corr.shape, dtype='u1')
        det.raw_mask[radius > rmax] = 1
    else:
        with h5py.File(args.mask, 'r') as fptr:
            det.raw_mask = fptr[args.mask_dset][:].astype('u1').flatten()
        if not args.dragonfly_mask:
            det.raw_mask = 2 - 2 * det.raw_mask

    det.detd = pm['detd'] / pm['pixsize']
    det.ewald_rad = pm['ewald_rad']
    det_file = output_folder + '/' + os.path.splitext(
        os.path.basename(args.h5_name))[0]
    try:
        import h5py
        det_file += '.h5'
    except ImportError:
        det_file += '.dat'
    logging.info('Writing detector file to %s', det_file)
    sys.stderr.write('Writing detector file to %s\n' % det_file)
    det.write(det_file)
Ejemplo n.º 6
0
def main():
    '''Parses command line arguments and config file to generate detector file'''
    logging.basicConfig(filename="recon.log",
                        level=logging.INFO,
                        format='%(asctime)s - %(levelname)s - %(message)s')
    parser = py_utils.MyArgparser(description="make detector")
    args = parser.special_parse_args()

    det_file = os.path.join(
        args.main_dir,
        read_config.get_filename(args.config_file, 'make_detector',
                                 'out_detector_file'))
    if args.yes:
        to_write = True
    else:
        to_write = py_utils.check_to_overwrite(det_file)
    logging.info("\n\nStarting make_detector....")
    logging.info(' '.join(sys.argv))

    if to_write:
        timer = py_utils.MyTimer()
        pm = read_config.get_detector_config(args.config_file, show=args.vb)  # pylint: disable=C0103
        q_pm = read_config.compute_q_params(pm['detd'],
                                            pm['dets_x'],
                                            pm['dets_y'],
                                            pm['pixsize'],
                                            pm['wavelength'],
                                            pm['ewald_rad'],
                                            show=args.vb)
        timer.reset_and_report(
            "Reading experiment parameters") if args.vb else timer.reset()

        qscaling = 1. / pm['wavelength'] / q_pm['q_sep']
        (x, y) = np.mgrid[0:pm['dets_x'], 0:pm['dets_y']]
        (x, y) = (x.flatten() - pm['detc_x'], y.flatten() - pm['detc_y'])
        norm = np.sqrt(x**2 + y**2 + (pm['detd'] / pm['pixsize'])**2)
        polar = read_config.compute_polarization(pm['polarization'], x, y,
                                                 norm)
        (qx, qy, qz) = (
            x * qscaling / norm,  # pylint: disable=C0103
            y * qscaling / norm,
            qscaling * (pm['detd'] / pm['pixsize'] / norm - 1.))
        logging.info('%15s:%10.4f', 'qmax',
                     np.sqrt(qx * qx + qy * qy + qz * qz).max())
        solid_angle = pm['detd'] / pm['pixsize'] / norm**3
        solid_angle = polar * solid_angle
        rad = np.sqrt(x * x + y * y)
        if pm['mask_fname'] is None:
            mask = np.zeros(solid_angle.shape, dtype='u1')
            mask[rad > min(pm['detc_x'], pm['detc_y'])] = 1
            mask[rad < pm['stoprad']] = 2
        else:
            mask = np.fromfile(pm['mask_fname'], '=u1')
            mask[(rad > min(pm['detc_x'], pm['detc_y'])) & (mask == 0)] = 1
        timer.reset_and_report(
            "Creating detector") if args.vb else timer.reset()

        with open(det_file, "w") as fptr:
            #fptr.write(str(pm['dets_x']*pm['dets_y']) + "\n")
            fptr.write("%d %.6f %.6f\n" %
                       (pm['dets_x'] * pm['dets_y'],
                        pm['detd'] / pm['pixsize'], pm['ewald_rad']))
            for par0, par1, par2, par3, par4 in zip(qx, qy, qz, solid_angle,
                                                    mask):
                txt = "%21.15e %21.15e %21.15e %21.15e %d\n" % (
                    par0, par1, par2, par3, par4)
                fptr.write(txt)
        timer.reset_and_report(
            "Writing detector") if args.vb else timer.reset()

        timer.report_time_since_beginning() if args.vb else timer.reset()
    else:
        pass
Ejemplo n.º 7
0
def main():
    '''Parses command line arguments and config file to generate detector file'''
    logging.basicConfig(filename="recon.log",
                        level=logging.INFO,
                        format='%(asctime)s - %(levelname)s - %(message)s')
    parser = py_utils.MyArgparser(description="make detector")
    args = parser.special_parse_args()

    det_file = os.path.join(
        args.main_dir,
        read_config.get_filename(args.config_file, 'make_detector',
                                 'out_detector_file'))
    if args.yes:
        to_write = True
    else:
        to_write = py_utils.check_to_overwrite(det_file)
    logging.info("\n\nStarting make_detector....")
    logging.info(' '.join(sys.argv))

    if to_write:
        timer = py_utils.MyTimer()
        pm = read_config.get_detector_config(args.config_file, show=args.vb)  # pylint: disable=C0103
        q_pm = read_config.compute_q_params(pm['detd'],
                                            pm['dets_x'],
                                            pm['dets_y'],
                                            pm['pixsize'],
                                            pm['wavelength'],
                                            pm['ewald_rad'],
                                            show=args.vb)
        timer.reset_and_report(
            "Reading experiment parameters") if args.vb else timer.reset()

        det = detector.Detector()
        qscaling = 1. / pm['wavelength'] / q_pm['q_sep']
        (x, y) = np.mgrid[0:pm['dets_x'], 0:pm['dets_y']]
        (x, y) = (x.flatten() - pm['detc_x'], y.flatten() - pm['detc_y'])
        norm = np.sqrt(x**2 + y**2 + (pm['detd'] / pm['pixsize'])**2)
        (det.qx, det.qy, det.qz) = (
            x * qscaling / norm,  # pylint: disable=C0103
            y * qscaling / norm,
            qscaling * (pm['detd'] / pm['pixsize'] / norm - 1.))
        logging.info('%15s:%10.4f', 'qmax',
                     np.sqrt(det.qx**2 + det.qy**2 + det.qz**2).max())

        polar = read_config.compute_polarization(pm['polarization'], x, y,
                                                 norm)
        det.corr = pm['detd'] / pm['pixsize'] / norm**3
        det.corr *= polar
        rad = np.sqrt(x * x + y * y)
        if pm['mask_fname'] is None:
            det.raw_mask = np.zeros(det.corr.shape, dtype='u1')
            det.raw_mask[rad > min(pm['detc_x'], pm['detc_y'])] = 1
            det.raw_mask[rad < pm['stoprad']] = 2
        else:
            det.raw_mask = np.fromfile(pm['mask_fname'], '=u1')
            det.raw_mask[(rad > min(pm['detc_x'], pm['detc_y']))
                         & (mask == 0)] = 1
        timer.reset_and_report(
            "Creating detector") if args.vb else timer.reset()

        det.detd = pm['detd'] / pm['pixsize']
        det.ewald_rad = pm['ewald_rad']
        det.write(det_file)
        timer.reset_and_report("Writing detector to %s" %
                               det_file) if args.vb else timer.reset()

        timer.report_time_since_beginning() if args.vb else timer.reset()
    else:
        pass