Exemple #1
0
    def read_experiment_file(self, experiment_file):

        ### open DIALS json file
        phil_scope_str='''
            experiments = 'example_refined_experiments.json'
              '''
        phil_scope = parse(phil_scope_str, process_includes=True)
        parser = OptionParser(
            phil=phil_scope,
            check_format=False,
            read_experiments=True)
        params, options = parser.parse_args(args=[experiment_file], show_diff_phil=True)
        experiments = flatten_experiments(params.input.experiments)
        exp_xtal = experiments.crystals()[0]

        ### define useful attributes
        self.crystal = exp_xtal
        uc = self.crystal.get_unit_cell()
        uc_nospace = str(uc).replace(" ", "")
        uc_nospace_noparen = uc_nospace[1:-1]
        self.unit_cell = uc_nospace_noparen
        self.space_group = self.crystal.get_space_group()
        self.laue_group = self.space_group.laue_group_type()
        # self.a_matrix = crystal.get_A()
        self.experiments = experiments
Exemple #2
0
  def run(self):
    '''Execute the script.'''

    from dials.util.options import flatten_reflections, flatten_experiments

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=False)
    reflections = flatten_reflections(params.input.reflections)
    experiments = flatten_experiments(params.input.experiments)

    # Try to load the models and data
    nexp = len(experiments)
    if nexp == 0:
      print "No Experiments found in the input"
      self.parser.print_help()
      return
    if len(reflections) == 0:
      print "No reflection data found in the input"
      self.parser.print_help()
      return
    if len(reflections) > 1:
      raise Sorry("Only one reflections list can be imported at present")
    reflections = reflections[0] # first reflection list
    reflections = reflections.select(reflections['id'] == 0) # first experiment
    if len(reflections) == 0:
      print "No reflection data for the first experiment found in the input"
      self.parser.print_help()
      return
    if len(experiments) > 1:
      raise Sorry("Only one experiment can be imported at present")
    experiment = experiments[0]

    om = ObservationManager(reflections, experiment)

    gp_idx = om.group_index
def run(args):

  from dials.util.options import OptionParser
  from dials.util.options import flatten_experiments
  from libtbx.utils import Sorry
  import libtbx.load_env

  usage = "%s [options] experiments.json" %libtbx.env.dispatcher_name

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_experiments=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=True)
  experiments = flatten_experiments(params.input.experiments)
  if len(experiments) <= 1:
    parser.print_help()
    return

  hkl = flex.miller_index(params.hkl)

  from dials.algorithms.indexing.compare_orientation_matrices import \
       show_rotation_matrix_differences
  show_rotation_matrix_differences(experiments.crystals(),
                                   miller_indices=hkl)
def run(args):
    import libtbx.load_env

    usage = "%s [options] experiment.json indexed.pickle" % libtbx.env.dispatcher_name

    parser = OptionParser(
        usage=usage,
        phil=phil_scope,
        read_reflections=True,
        read_experiments=True,
        check_format=False,
        epilog=help_message,
    )

    params, options = parser.parse_args(show_diff_phil=True)

    reflections = flatten_reflections(params.input.reflections)
    experiments = flatten_experiments(params.input.experiments)
    if len(reflections) == 0 or len(experiments) == 0:
        parser.print_help()
        return
    assert len(reflections) == 1
    assert len(experiments) == 1
    experiment = experiments[0]
    reflections = reflections[0]

    test_P1_crystal_indexing(reflections, experiment, params)
    test_crystal_pointgroup_symmetry(reflections, experiment, params)
Exemple #5
0
  def run(self):
    ''' Parse the options. '''
    from dials.util.options import flatten_experiments, flatten_reflections
    # Parse the command line arguments
    params, options = self.parser.parse_args(show_diff_phil=True)
    self.params = params
    experiments = flatten_experiments(params.input.experiments)
    reflections = flatten_reflections(params.input.reflections)

    assert len(reflections) == len(experiments) == 1
    reflections = reflections[0]
    exp = experiments[0]

    from dials.algorithms.indexing import index_reflections
    from dials.algorithms.indexing.indexer import indexer_base

    reflections['id'] = flex.int(len(reflections), -1)
    reflections['imageset_id'] = flex.int(len(reflections), 0)
    reflections = indexer_base.map_spots_pixel_to_mm_rad(reflections, exp.detector, exp.scan)

    indexer_base.map_centroids_to_reciprocal_space(
      reflections, exp.detector, exp.beam, exp.goniometer,)

    index_reflections(reflections,
                      experiments, params.d_min,
                      tolerance=0.3)
    indexed_reflections = reflections.select(reflections['miller_index'] != (0,0,0))
    print "Indexed %d reflections out of %d"%(len(indexed_reflections), len(reflections))
    easy_pickle.dump("indexedstrong.pickle", indexed_reflections)
def run(args):
  from dials.util.options import OptionParser
  from dials.util.options import flatten_experiments
  from dials.util.options import flatten_reflections
  import libtbx.load_env

  usage = "%s [options] integrated.pickle experiments.json" % (
    libtbx.env.dispatcher_name)

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_experiments=True,
    read_reflections=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=False)
  experiments = flatten_experiments(params.input.experiments)
  reflections = flatten_reflections(params.input.reflections)

  if len(experiments) != 1 or len(reflections) != 1:
    parser.print_help()
    exit()

  if not 'shoebox' in reflections[0]:
    print 'Please add shoeboxes to reflection pickle'
    exit()

  results = main(reflections[0], experiments[0], params)

  if results:
    print 'mean result: %.3f' % (sum(results) / len(results))
Exemple #7
0
def run(args):

  from dials.util.options import OptionParser
  from dials.util.options import flatten_datablocks
  from dials.util.options import flatten_experiments
  import libtbx.load_env

  usage = "%s [options] datablock.json" %(
    libtbx.env.dispatcher_name)

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_datablocks=True,
    read_experiments=True,
    check_format=True,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=True)
  datablocks = flatten_datablocks(params.input.datablock)
  experiments = flatten_experiments(params.input.experiments)

  if (len(datablocks) == 0 and len(experiments) == 0):
    parser.print_help()
    exit(0)

  if len(datablocks) == 0 and len(experiments) > 0:
    imagesets = experiments.imagesets()
  else:
    imagesets = []
    for datablock in datablocks:
      imagesets.extend(datablock.extract_imagesets())

  assert len(imagesets) == 1
  imageset = imagesets[0]
  gonio = imageset.get_goniometer()
  if not params.detector_distance:
    detector = imageset.get_detector()
    if len(detector) > 1:
      params.detector_distance = detector.hierarchy().get_directed_distance()
    else:
      params.detector_distance = detector[0].get_directed_distance()
  if params.angle:
    assert len(params.angle) == len(gonio.get_angles())
  else:
    for angle in gonio.get_angles():
      params.angle.append(angle)

  import wxtbx.app
  a = wxtbx.app.CCTBXApp(0)
  a.settings = params
  f = ExperimentViewer(
    None, -1, "Experiment viewer", size=(1024,768))
  f.load_imageset(imageset)
  f.Show()
  a.SetTopWindow(f)
  #a.Bind(wx.EVT_WINDOW_DESTROY, lambda evt: tb_icon.Destroy(), f)
  a.MainLoop()
Exemple #8
0
def run(args):
  from dials.util import log
  import libtbx.load_env
  usage = "%s experiments.json indexed.pickle [options]" %libtbx.env.dispatcher_name


  from dials.util.options import OptionParser
  from dials.util.options import flatten_reflections
  from dials.util.options import flatten_experiments
  from dials.array_family import flex

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_experiments=True,
    read_reflections=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=False)

  # Configure the logging
  #log.config(info=params.output.log, debug=params.output.debug_log)

  from dials.util.version import dials_version
  logger.info(dials_version())

  # Log the diff phil
  diff_phil = parser.diff_phil.as_str()
  if diff_phil is not '':
    logger.info('The following parameters have been modified:\n')
    logger.info(diff_phil)

  experiments = flatten_experiments(params.input.experiments)
  reflections = flatten_reflections(params.input.reflections)
  assert(len(reflections) == 1)
  reflections = reflections[0]

  if len(experiments) == 0:
    parser.print_help()
    return

  #from dials.command_line import refine
  #params = refine.phil_scope.extract()
  indexed_reflections = reflections.select(reflections['id'] > -1)
  from dials.algorithms.refinement import RefinerFactory
  refiner = RefinerFactory.from_parameters_data_experiments(
    params, indexed_reflections, experiments)
  #refiner.run()
  rmsds = refiner.rmsds()
  import math
  xy_rmsds = math.sqrt(rmsds[0]**2 + rmsds[1]**2)

  print rmsds



  return
def run(args):

  from dials.util.options import OptionParser
  from dials.util.options import flatten_datablocks
  from dials.util.options import flatten_experiments
  from dials.util.options import flatten_reflections

  parser = OptionParser(
    phil=master_phil,
    read_datablocks=True,
    read_experiments=True,
    read_reflections=True,
    check_format=False)

  params, options = parser.parse_args(show_diff_phil=True)
  datablocks = flatten_datablocks(params.input.datablock)
  experiments = flatten_experiments(params.input.experiments)
  reflections = flatten_reflections(params.input.reflections)[0]
  if len(params.input.reflections) == 2:
    reflections2 = flatten_reflections(params.input.reflections)[1]
  else:
    reflections2 = None

  # find the reflections in the second set that DO NOT match those in the
  # first set
  mask, _ = reflections2.match_with_reference(reflections)
  reflections2 = reflections2.select(~mask)
  print "{0} reflections from the second set do not match the first". \
    format(len(reflections2))
  #reflections2 = reflections2.select(reflections2["miller_index"] == (-7,2,-25))

  if len(datablocks) == 0:
    if len(experiments) > 0:
      imagesets = experiments.imagesets()
    else:
      parser.print_help()
      return
  elif len(datablocks) > 1:
    raise Sorry("Only one DataBlock can be processed at a time")
  else:
    imagesets = datablocks[0].extract_imagesets()

  if len(imagesets) > 1:
    raise Sorry("Only one ImageSet can be processed at a time")
  imageset = imagesets[0]

  import wxtbx.app
  a = wxtbx.app.CCTBXApp(0)
  a.settings = params
  f = PredRelpViewer(
    None, -1, "Prediction reciprocal lattice viewer", size=(1024,768))
  f.load_reflections2(reflections2)
  f.load_models(imageset, reflections)
  f.Show()
  a.SetTopWindow(f)
  #a.Bind(wx.EVT_WINDOW_DESTROY, lambda evt: tb_icon.Destroy(), f)
  a.MainLoop()
def run(args):

  from dials.util.options import OptionParser
  from dials.util.options import flatten_datablocks
  from dials.util.options import flatten_experiments
  from dials.util.options import flatten_reflections
  import libtbx.load_env

  usage = "%s [options] datablock.json reflections.pickle" %(
    libtbx.env.dispatcher_name)

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_datablocks=True,
    read_experiments=True,
    read_reflections=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=True)
  datablocks = flatten_datablocks(params.input.datablock)
  experiments = flatten_experiments(params.input.experiments)
  reflections = flatten_reflections(params.input.reflections)

  if (len(datablocks) == 0 and len(experiments) == 0) or len(reflections) == 0:
    parser.print_help()
    exit(0)

  if len(datablocks) == 0 and len(experiments) > 0:
    imagesets = experiments.imagesets()
  else:
    imagesets = []
    for datablock in datablocks:
      imagesets.extend(datablock.extract_imagesets())

  if len(reflections) > 1:
    assert len(reflections) == len(imagesets)
    from scitbx.array_family import flex
    for i in range(len(reflections)):
      reflections[i]['imageset_id'] = flex.int(len(reflections[i]), i)
      if i > 0:
        reflections[0].extend(reflections[i])

  reflections = reflections[0]

  import wxtbx.app
  a = wxtbx.app.CCTBXApp(0)
  a.settings = params
  f = ReciprocalLatticeViewer(
    None, -1, "Reflection data viewer", size=(1024,768))
  f.load_models(imagesets, reflections)
  f.Show()
  a.SetTopWindow(f)
  #a.Bind(wx.EVT_WINDOW_DESTROY, lambda evt: tb_icon.Destroy(), f)
  a.MainLoop()
  def run(self):
    params, options = self.parser.parse_args(show_diff_phil=True)
    experiments = flatten_experiments(params.input.experiments)

    detector = experiments[0].detector

    metro = map_detector_to_basis_dict(detector)
    write_cspad_cbf(None, metro, 'cbf', None, params.output_def_file, None, detector.hierarchy().get_distance(), header_only=True)

    print "Done"
  def run(self):
    ''' Perform the integration. '''
    from dials.util.command_line import heading
    from dials.util.options import flatten_experiments
    from dials.util import log
    from time import time
    from libtbx.utils import Sorry
    from dials.array_family import flex

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=False)
    experiments = flatten_experiments(params.input.experiments)
    if len(experiments) == 0:
      self.parser.print_help()
      return

    assert len(experiments) == 1
    imageset = experiments[0].imageset
    beam = experiments[0].beam
    detector = experiments[0].detector
    goniometer = experiments[0].goniometer
    assert len(detector) == 1

    # Configure logging
    log.config()

    from dials.algorithms.background.gmodel import PolarTransform
    import cPickle as pickle
    model = pickle.load(open(params.model))
    image = model.data(0)
    mask = flex.bool(image.accessor(), True)

    # Do the transformation
    transform = PolarTransform(beam, detector[0], goniometer)
    result = transform.to_polar(image, mask)
    data = result.data()
    mask = result.mask()

    pickle.dump((data, mask), open(params.output.data, "w"))

    from matplotlib import pylab
    vmax = sorted(list(data))[int(0.99 * len(data))]
    figure = pylab.figure(figsize=(6,4))
    pylab.imshow(
      data.as_numpy_array(),
      interpolation = 'none',
      vmin          = 0,
      vmax          = vmax)
    ax1 = pylab.gca()
    ax1.get_xaxis().set_visible(False)
    ax1.get_yaxis().set_visible(False)
    cb = pylab.colorbar()
    cb.ax.tick_params(labelsize=8)
    logger.info("Saving polar model %s" % (params.output.image))
    pylab.savefig("%s" % (params.output.image), dpi=600, bbox_inches='tight')
def run(args):
  import libtbx.load_env
  usage = "%s experiments.json [options]" %libtbx.env.dispatcher_name

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_experiments=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=True)
  experiments = flatten_experiments(params.input.experiments)
  if len(experiments) == 0:
    parser.print_help()
    return
  elif len(experiments) > 1:
    raise Sorry("More than one experiment present")

  assert len(params.miller_index), "Must specify at least one miller_index to predict."

  experiment = experiments[0]

  reflections = flex.reflection_table()
  miller_indices = flex.miller_index()
  entering_flags = flex.bool()
  for mi in params.miller_index:
    miller_indices.append(mi)
    miller_indices.append(mi)
    entering_flags.append(True)
    entering_flags.append(False)
  reflections['miller_index'] = miller_indices
  reflections['entering'] = entering_flags
  reflections['id'] = flex.size_t(len(reflections), 0)

  if params.expand_to_p1:
    from cctbx.miller import expand_to_p1_iselection
    proxy = expand_to_p1_iselection(
      experiment.crystal.get_space_group(),
      anomalous_flag=True,
      indices=miller_indices,
      build_iselection=True)
    reflections = reflections.select(proxy.iselection)
    reflections['miller_index'] = proxy.indices

  from dials.algorithms.refinement.prediction.managed_predictors import ExperimentsPredictor
  predictor = ExperimentsPredictor([experiment])
  predicted = predictor.predict(reflections)

  zmin, zmax = experiment.scan.get_array_range()
  z = predicted['xyzcal.px'].parts()[2]
  predicted = predicted.select((z >= zmin) & (z <= zmax))

  show_predictions(predicted)
  def __init__(self, pickle_name, json_name):
    # load the integration.pickle file (reflection table) into memory and
    # load the experiments.json file (json) into memory, piecewise.
    # check_format=False because we don't wont to load any imagesets in the
    # experiement list
    importer = Importer([pickle_name, json_name], read_experiments=True, read_reflections=True, check_format=False)
    if importer.unhandled:
      print "unable to process:", importer.unhandled

    ConstructFrame.__init__(self, flatten_reflections(importer.reflections)[0],
                                  flatten_experiments(importer.experiments)[0])
Exemple #15
0
def run(args):

  from dials.util.options import OptionParser
  from dials.util.options import flatten_datablocks
  from dials.util.options import flatten_experiments
  from dials.util.options import flatten_reflections
  from dials.util import log

  usage = "%s [options] datablock.json reflections.pickle" %(
    libtbx.env.dispatcher_name)

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_datablocks=True,
    read_experiments=True,
    read_reflections=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args()
  datablocks = flatten_datablocks(params.input.datablock)
  experiments = flatten_experiments(params.input.experiments)
  reflections = flatten_reflections(params.input.reflections)

  if (len(datablocks) == 0 and len(experiments) == 0) or len(reflections) == 0:
    parser.print_help()
    exit(0)

  ## Configure the logging
  #log.config(info='dials.rl_png.log')

  # Log the diff phil
  diff_phil = parser.diff_phil.as_str()
  if diff_phil is not '':
    logger.info('The following parameters have been modified:\n')
    logger.info(diff_phil)

  reflections = reflections[0]

  if len(datablocks) == 0 and len(experiments) > 0:
    imagesets = experiments.imagesets()
  else:
    imagesets = []
    for datablock in datablocks:
      imagesets.extend(datablock.extract_imagesets())

  f = ReciprocalLatticeJson(settings=params)
  f.load_models(imagesets, reflections)
  f.as_json(filename=params.output.json, compact=params.output.compact)
  print
Exemple #16
0
def run(args):

  from dials.util.options import OptionParser
  from dials.util.options import flatten_datablocks
  from dials.util.options import flatten_experiments
  import libtbx.load_env

  usage = "%s [options] datablock.json | experiments.json" %(
    libtbx.env.dispatcher_name)

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_datablocks=True,
    read_experiments=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=True)
  experiments = flatten_experiments(params.input.experiments)
  datablocks = flatten_datablocks(params.input.datablock)

  if len(experiments) == 0 and len(datablocks) == 0:
    parser.print_help()
    exit(0)

  from dials.command_line.dials_import import ManualGeometryUpdater
  update_geometry = ManualGeometryUpdater(params)


  if len(experiments):
    imagesets = experiments.imagesets()

  elif len(datablocks):

    assert len(datablocks) == 1
    imagesets = datablocks[0].extract_imageset()

  for imageset in imagesets:
    imageset_new = update_geometry(imageset)
    imageset.set_detector(imageset_new.get_detector())
    imageset.set_beam(imageset_new.get_beam())
    imageset.set_goniometer(imageset_new.get_goniometer())
    imageset.set_scan(imageset_new.get_scan())

  from dxtbx.serialize import dump
  if len(experiments):
    print "Saving modified experiments to %s" %params.output.experiments
    dump.experiment_list(experiments, params.output.experiments)
  elif len(datablocks):
    raise NotImplemented
def run(args):
  import libtbx.load_env
  from dials.array_family import flex
  from dials.util import log
  from dials.util.version import dials_version

  usage = "%s [options] experiment.json indexed.pickle" % \
    libtbx.env.dispatcher_name

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_reflections=True,
    read_experiments=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=True)

  # Configure the logging
  log.config(info=params.output.log, debug=params.output.debug_log)
  logger.info(dials_version())

  reflections = flatten_reflections(params.input.reflections)
  experiments = flatten_experiments(params.input.experiments)
  if len(reflections) == 0 or len(experiments) == 0:
    parser.print_help()
    return
  assert(len(reflections) == 1)
  assert(len(experiments) == 1)
  experiment = experiments[0]
  reflections = reflections[0]

  # remove reflections with 0, 0, 0 index
  zero = (reflections['miller_index'] == (0, 0, 0))
  logger.info('Removing %d unindexed reflections' % zero.count(True))
  reflections = reflections.select(~zero)

  h, k, l = reflections['miller_index'].as_vec3_double().parts()

  h = h.iround()
  k = k.iround()
  l = l.iround()

  logger.info('Range on h: %d to %d' % (flex.min(h), flex.max(h)))
  logger.info('Range on k: %d to %d' % (flex.min(k), flex.max(k)))
  logger.info('Range on l: %d to %d' % (flex.min(l), flex.max(l)))

  test_P1_crystal_indexing(reflections, experiment, params)
  test_crystal_pointgroup_symmetry(reflections, experiment, params)
Exemple #18
0
  def run(self):
    '''Execute the script.'''

    from dials.util.options import flatten_reflections, flatten_experiments
    from libtbx.utils import Sorry
    from dials.array_family import flex

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=True)

    # Try to load the models and data
    if not params.input.experiments:
      print "No Experiments found in the input"
      self.parser.print_help()
      return
    if params.input.reflections:
      if len(params.input.reflections) != len(params.input.experiments):
        raise Sorry("The number of input reflections files does not match the "
          "number of input experiments")

    experiments = flatten_experiments(params.input.experiments)
    if params.input.reflections:
      reflections = flatten_reflections(params.input.reflections)[0]
    else:
      reflections = None

    import math
    experiments_template = "%s_%%0%sd.json" %(
      params.output.experiments_prefix,
      int(math.floor(math.log10(len(experiments))) + 1))
    reflections_template = "%s_%%0%sd.pickle" %(
      params.output.reflections_prefix,
      int(math.floor(math.log10(len(experiments))) + 1))

    for i, experiment in enumerate(experiments):
      from dxtbx.model.experiment.experiment_list import ExperimentList
      from dxtbx.serialize import dump
      experiment_filename = experiments_template %i
      print 'Saving experiment %d to %s' %(i, experiment_filename)
      dump.experiment_list(ExperimentList([experiment]), experiment_filename)

      if reflections is not None:
        reflections_filename = reflections_template %i
        print 'Saving reflections for experiment %d to %s' %(i, reflections_filename)
        ref_sel = reflections.select(reflections['id'] == i)
        ref_sel['id'] = flex.int(len(ref_sel), 0)
        ref_sel.as_pickle(reflections_filename)

    return
Exemple #19
0
  def run(self):
    '''Execute the script.'''
    from dials.util.command_line import Command
    from dials.array_family import flex
    from dials.util.options import flatten_experiments

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=True)

    # Check the number of experiments
    experiments = flatten_experiments(params.input.experiments)
    if len(experiments) == 0:
      self.parser.print_help()
      return

    predicted_all = flex.reflection_table()

    for i_expt, expt in enumerate(experiments):
      if params.buffer_size > 0:
        # Hack to make the predicter predict reflections outside of the range
        # of the scan
        scan = expt.scan
        image_range = scan.get_image_range()
        oscillation = scan.get_oscillation()
        scan.set_image_range((image_range[0]-params.buffer_size,
                              image_range[1]+params.buffer_size))
        scan.set_oscillation((oscillation[0]-params.buffer_size*oscillation[1],
                              oscillation[1]))

      # Populate the reflection table with predictions
      predicted = flex.reflection_table.from_predictions(
        expt,
        force_static=params.force_static,
        dmin=params.d_min)
      predicted['id'] = flex.int(len(predicted), i_expt)
      predicted_all.extend(predicted)

    try:
      predicted_all.compute_bbox(experiments)
    except Exception:
      pass

    # Save the reflections to file
    Command.start('Saving {0} reflections to {1}'.format(
        len(predicted_all), params.output))
    predicted_all.as_pickle(params.output)
    Command.end('Saved {0} reflections to {1}'.format(
        len(predicted_all), params.output))
    def run(self):
        params, options = self.parser.parse_args(show_diff_phil=True)
        datablocks = flatten_datablocks(params.input.datablock)
        experiments = flatten_experiments(params.input.experiments)
        reflections = flatten_reflections(params.input.reflections)
        if len(reflections) > 0:
            reflections = reflections[0]
        else:
            reflections = None

        all_detectors = []
        for db in datablocks:
            all_detectors.extend(db.unique_detectors())

        all_detectors.extend(experiments.detectors())
        display_detectors(all_detectors[: min(len(all_detectors), 10)], reflections=reflections)
  def run(self):
    '''Execute the script.'''

    from dials.util.options import flatten_experiments
    from libtbx.utils import Sorry
    from dials.array_family import flex

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=True)

    # Try to load the experiments
    if not params.input.experiments:
      print "No Experiments found in the input"
      self.parser.print_help()
      return

    experiments = flatten_experiments(params.input.experiments)
    print "{0} experiments loaded".format(len(experiments))

    us0_vecs = self.extract_us0_vecs(experiments)
    e_vecs = self.extract_rotation_axes(experiments)

    angles = [us0.angle(e, deg=True) for us0, e in zip(us0_vecs, e_vecs)]

    fmt = "{:." + str(params.print_precision) + "f}"
    header = ['Exp\nid','Beam direction', 'Rotation axis', 'Angle (deg)']
    rows = []
    for iexp, (us0, e, ang) in enumerate(zip(us0_vecs, e_vecs, angles)):
      beam_str = " ".join([fmt] * 3).format(*us0.elems)
      e_str = " ".join([fmt] * 3).format(*e.elems)
      rows.append([str(iexp), beam_str, e_str, fmt.format(ang)])
    if len(rows) > 0:
      st = simple_table(rows, header)
      print st.format()

    # mean and sd
    if len(rows) > 1:
      angles = flex.double(angles)
      mv = flex.mean_and_variance(angles)

      print "Mean and standard deviation of the angle"
      print (fmt.format(mv.mean()) + " +/- " + fmt.format(
        mv.unweighted_sample_standard_deviation()))
      print

    return
Exemple #22
0
  def run(self):
    """lurrr"""
    from dials.util.options import flatten_experiments

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=True, args=None)
    experiments = flatten_experiments(params.input.experiments)
    if len(experiments) == 0:
      print "No experiments given"
      return
    elif len(experiments.imagesets()) > 1 or len(experiments.detectors()) > 1:
      raise RuntimeError('experiment list contains > 1 imageset or detector')

    params.prediction.dmin = 0.67
    params.prediction.dmax = 23
    if (params.prediction.dmin is None) or (params.prediction.dmax is None):
      integrated = pickle.load(open('/home/wra62962/local/testsets/Ni_dppe_NO2_2.dials.sweep3/integrated.pickle', 'rb'))
      #integrated = pickle.load(open('/home/wra62962/local/testsets/TestsetMX.300.dials/integrated.pickle', 'rb'))
      if params.prediction.dmin is None:
        params.prediction.dmin = min(integrated["d"])
      if params.prediction.dmax is None:
        params.prediction.dmax = max(integrated["d"])

    print "Considering reflections with resolution %.2f - %.2f Ang" % (params.prediction.dmin, params.prediction.dmax)

    evaluator = self.StrategyEvaluator(experiments,
                                       self.SimpleGeometricEvaluationFunctionFactory,
                                       #self.SimpleEvaluationFunctionFactory,
                                       params.prediction.dmin,
                                       params.prediction.dmax)

    strategylist = self.getFixedStrategylist()
    results = []

    for strategy in strategylist:
      print
      print "%s strategy: " % strategy['name']
      quality = evaluator(strategy['strategy'])
      quality['name'] = strategy['name']
      results.append(quality)

    print "%30s   Comp   Mul  Score  Sweep  Sc/deg" % "Strategy"
    for r in sorted(results, key=(lambda x: x['score']), reverse=True):
      print "%30s: %5.1f  %4.1f  %5d  %4d%s  %5.1f" %\
            (r['name'], r['completeness'], r['multiplicity'], r['score'], r['degrees'], " deg",
             r['score'] / r['degrees'])
Exemple #23
0
def run(args):
  import libtbx.load_env
  usage = """\
%s datablock.json reflections.pickle [options]""" %libtbx.env.dispatcher_name
  from dials.util.options import OptionParser
  from dials.util.options import flatten_datablocks
  from dials.util.options import flatten_experiments
  from dials.util.options import flatten_reflections
  from scitbx.array_family import flex
  from scitbx import matrix
  from libtbx.phil import command_line
  from libtbx.utils import Sorry
  parser = OptionParser(
    usage=usage,
    phil=master_phil_scope,
    read_datablocks=True,
    read_experiments=True,
    read_reflections=True,
    check_format=False)

  params, options = parser.parse_args(show_diff_phil=True)
  datablocks = flatten_datablocks(params.input.datablock)
  reflections = flatten_reflections(params.input.reflections)
  experiments = flatten_experiments(params.input.experiments)
  if len(datablocks) == 1:
    imageset = datablocks[0].extract_imagesets()[0]
  elif len(datablocks) > 1:
    raise Sorry("Only one DataBlock can be processed at a time")
  elif len(experiments.imagesets()) > 0:
    imageset = experiments.imagesets()[0]
    imageset.set_detector(experiments[0].detector)
    imageset.set_beam(experiments[0].beam)
    imageset.set_goniometer(experiments[0].goniometer)
  else:
    parser.print_help()
    return

  detector = imageset.get_detector()
  scan = imageset.get_scan()

  panel_origin_shifts = {0: (0,0,0)}
  try:
    hierarchy = detector.hierarchy()
  except AttributeError, e:
    hierarchy = None
Exemple #24
0
def matrixForFilename(filename, output):
	arguments = []
	arguments.append(filename)

	from dials.util.options import OptionParser
	from dials.util.options import flatten_experiments
	from libtbx.utils import Abort

	parser = OptionParser(
	read_experiments=True,
	check_format=False)

	params, options = parser.parse_args(args=arguments, show_diff_phil=True)
	experiments = flatten_experiments(params.input.experiments)

	path = experiments[0].imageset.get_path(0)
	print "Image", path, "has", len(experiments), "experiments."
	printExperiments(experiments, filename, output)
Exemple #25
0
def matrixForFilename(filename, output):
	rootname_stem = rootnameStem(filename)
	
	arguments = []
	arguments.append(filename)

	from dials.util.options import OptionParser
	from dials.util.options import flatten_experiments
	from libtbx.utils import Abort

	parser = OptionParser(
	read_experiments=True,
	check_format=False)

	params, options = parser.parse_args(args=arguments, show_diff_phil=True)
	experiments = flatten_experiments(params.input.experiments)

	printExperiments(experiments, filename, output)
 def __init__(self, path, json=None, pickle_ext=None, json_ext=None):
   if json is None:
     json = find_json(path, pickle_ext, json_ext)
   if json is None:
     importer = Importer([path], read_experiments=False, read_reflections=True, check_format=False)
     print "unable to find experiment list"
     self.experiments = None
   else:
     importer = Importer([path, json], read_experiments=True, read_reflections=True, check_format=False)
     try:
       self.experiments = flatten_experiments(importer.experiments)[0]
     except IndexError:
       print "unable to read experiment list"
       self.experiments = None
   try:
     self.reflections = flatten_reflections(importer.reflections)[0]
   except IndexError:
     print "unable to read reflection table"
     self.reflections = None
Exemple #27
0
  def run(self):
    '''Execute the script.'''
    from dials.util.command_line import Command
    from dials.array_family import flex
    from dials.util.options import flatten_experiments

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=True)

    # Check the number of experiments is at least 2
    experiments = flatten_experiments(params.input.experiments)
    if len(experiments) < 2:
      self.parser.print_help()
      return

    detectors = [experiment.detector[0] for experiment in experiments]

    from itertools import combinations

    for pair in combinations(detectors, 2):
      determine_axis(pair, params)
  def run(self):
    ''' Analyse the background '''
    from dials.util.command_line import heading
    from dials.util.options import flatten_experiments
    from dials.util import log
    from logging import info, debug
    from time import time
    from libtbx.utils import Sorry

    # Parse the command line
    params, options = self.parser.parse_args(show_diff_phil=False)
    experiments = flatten_experiments(params.input.experiments)
    if len(experiments) == 0:
      self.parser.print_help()
      return

    assert len(experiments) == 1

    # Get the imageset
    imageset = experiments[0].imageset

    total_image = None
    total_mask = None
    for i in range(len(imageset)):
      print i
      image = imageset.get_raw_data(i)
      mask = imageset.get_mask(i)
      if total_image is None:
        total_image = image[0]
        total_mask = mask[0]
      else:
        total_image += image[0]
    total_image /= len(imageset)
    print min(total_image)
    print max(total_image)
    print sum(total_image) / len(total_image)

    from matplotlib import pylab
    pylab.imshow(total_image.as_numpy_array(), vmin=0,vmax=2)
    pylab.show()
Exemple #29
0
def run(args):

  from dials.util.options import OptionParser
  from dials.util.options import flatten_datablocks
  from dials.util.options import flatten_experiments
  from dials.util.options import flatten_reflections
  import libtbx.load_env

  usage = "%s [options] datablock.json reflections.pickle" %(
    libtbx.env.dispatcher_name)

  parser = OptionParser(
    usage=usage,
    phil=phil_scope,
    read_datablocks=True,
    read_experiments=True,
    read_reflections=True,
    check_format=False,
    epilog=help_message)

  params, options = parser.parse_args(show_diff_phil=True)
  datablocks = flatten_datablocks(params.input.datablock)
  experiments = flatten_experiments(params.input.experiments)
  reflections = flatten_reflections(params.input.reflections)

  if (len(datablocks) == 0 and len(experiments) == 0) or len(reflections) == 0:
    parser.print_help()
    exit(0)

  reflections = reflections[0]

  if len(datablocks) == 0 and len(experiments) > 0:
    imagesets = experiments.imagesets()
  else:
    imagesets = []
    for datablock in datablocks:
      imagesets.extend(datablock.extract_imagesets())

  spot_resolution_shells(imagesets, reflections, params)
Exemple #30
0
  def run(self):
    # load at least two detectors from the command line
    params, options = self.parser.parse_args(show_diff_phil=True)
    datablocks  = flatten_datablocks(params.input.datablock)
    experiments = flatten_experiments(params.input.experiments)

    # collect all detectors found
    all_detectors = []
    for db in datablocks:
      all_detectors.extend(db.unique_detectors())

    all_detectors.extend(experiments.detectors())

    assert len(all_detectors) >= 2

    a = all_detectors[0]
    b = all_detectors[1]

    level = 0
    pga = a.hierarchy()
    pgb = b.hierarchy()

    while True:
      # starting at the top of the hierarchy, show diffs in local origins at each level
      print "Level", level
      oa = col(pga.get_local_origin())
      ob = col(pgb.get_local_origin())

      print "  Detector a", oa.elems
      print "  Detector b", ob.elems
      print "  Diffs", (ob-oa).elems

      if hasattr(pga, 'children'):
        pga = pga[0]
        pgb = pgb[0]
        level += 1
      else:
        break