def exercise_core_LS(target_class, verbose):
    n_refl = 10
    f_calc = flex.polar(
        flex.random_double(n_refl) * 10 - 5,
        flex.random_double(n_refl) * 10 - 5)
    f_obs = flex.abs(f_calc) + (flex.random_double(n_refl) * 2 - 1)
    weights = flex.random_double(n_refl)
    r = xray.targets_least_squares_residual(f_obs, weights, f_calc, True, 0)
    scale_factor = r.scale_factor()
    gr_ana = r.derivatives()
    gr_fin = flex.complex_double()
    eps = 1.e-6
    for i_refl in xrange(n_refl):
        gc = []
        for i_part in [0, 1]:
            fc0 = f_calc[i_refl]
            ts = []
            for signed_eps in [eps, -eps]:
                if (i_part == 0):
                    f_calc[i_refl] = complex(fc0.real + signed_eps, fc0.imag)
                else:
                    f_calc[i_refl] = complex(fc0.real, fc0.imag + signed_eps)
                r = xray.targets_least_squares_residual(
                    f_obs, weights, f_calc, False, scale_factor)
                ts.append(r.target())
            f_calc[i_refl] = fc0
            gc.append((ts[0] - ts[1]) / (2 * eps))
        gr_fin.append(complex(*gc))
    if (verbose):
        print "ana:", list(gr_ana)
        print "fin:", list(gr_fin)
    assert approx_equal(gr_fin, gr_ana)
def exercise_core_LS(target_class, verbose):
  n_refl = 10
  f_calc = flex.polar(
    flex.random_double(n_refl)*10-5,
    flex.random_double(n_refl)*10-5)
  f_obs = flex.abs(f_calc) + (flex.random_double(n_refl)*2-1)
  weights = flex.random_double(n_refl)
  r = xray.targets_least_squares_residual(
    f_obs, weights, f_calc, True, 0)
  scale_factor = r.scale_factor()
  gr_ana = r.derivatives()
  gr_fin = flex.complex_double()
  eps = 1.e-6
  for i_refl in xrange(n_refl):
    gc = []
    for i_part in [0,1]:
      fc0 = f_calc[i_refl]
      ts = []
      for signed_eps in [eps,-eps]:
        if (i_part == 0):
          f_calc[i_refl] = complex(fc0.real + signed_eps, fc0.imag)
        else:
          f_calc[i_refl] = complex(fc0.real, fc0.imag + signed_eps)
        r = xray.targets_least_squares_residual(
          f_obs, weights, f_calc, False, scale_factor)
        ts.append(r.target())
      f_calc[i_refl] = fc0
      gc.append((ts[0]-ts[1])/(2*eps))
    gr_fin.append(complex(*gc))
  if (verbose):
    print "ana:", list(gr_ana)
    print "fin:", list(gr_fin)
  assert approx_equal(gr_fin, gr_ana)
def shift_all(structure_ideal, f_obs, anomalous_flag):
  sh = shifted_site(None, structure_ideal, 0, 0, 0.01)
  sh = shifted_u_iso(None, sh.structure_shifted, 0, 0.05)
  sh = shifted_u_star(None, sh.structure_shifted, 0, 0, 0.0001)
  sh = shifted_occupancy(None, sh.structure_shifted, 0, 0.2)
  if (anomalous_flag):
    sh = shifted_fdp(None, sh.structure_shifted, 0, 2)
  sh = shifted_fp(f_obs, sh.structure_shifted, 0, -0.2)
  ls = xray.targets_least_squares_residual(
    f_obs.data(), sh.f_calc.data(), True, 1)
  return sh, ls
Пример #4
0
def site(structure_ideal, d_min, f_obs, verbose=0):
    sh = shifted_site(f_obs, structure_ideal, 0, 0, 0.01)
    if (0 or verbose):
        print("site")
        sh.structure_shifted.show_summary().show_scatterers()
        print()
    ls = xray.targets_least_squares_residual(f_obs.data(), sh.f_calc.data(),
                                             True, 1)
    gradient_flags = randomize_gradient_flags(
        xray.structure_factors.gradient_flags(site=True),
        f_obs.anomalous_flag())
    xray.set_scatterer_grad_flags(scatterers=sh.structure_shifted.scatterers(),
                                  site=gradient_flags.site,
                                  u_iso=gradient_flags.u_iso,
                                  u_aniso=gradient_flags.u_aniso,
                                  occupancy=gradient_flags.occupancy,
                                  fp=gradient_flags.fp,
                                  fdp=gradient_flags.fdp)
    sfd = xray.structure_factors.gradients_direct(
        xray_structure=sh.structure_shifted,
        u_iso_refinable_params=None,
        miller_set=f_obs,
        d_target_d_f_calc=ls.derivatives(),
        n_parameters=0)
    re = resampling(miller_set=f_obs)
    map0 = re(xray_structure=sh.structure_shifted,
              u_iso_refinable_params=None,
              dp=miller.array(miller_set=f_obs, data=ls.derivatives()),
              n_parameters=0,
              verbose=verbose)
    sfd_d_target_d_site_cart = sfd.d_target_d_site_cart()
    top_gradient = None
    for i_scatterer, scatterer in enumerate(sh.structure_shifted.scatterers()):
        for i_xyz in (0, 1, 2):
            direct_summ = sfd_d_target_d_site_cart[i_scatterer][i_xyz]
            if (top_gradient is None): top_gradient = direct_summ
            fast_gradie = map0.d_target_d_site_cart()[i_scatterer][i_xyz]
            match = judge(scatterer, "site", direct_summ, fast_gradie,
                          top_gradient)
            if (0 or verbose):
                print("direct summ[%d][%d]: " % (i_scatterer, i_xyz),
                      direct_summ)
                print("fast gradie[%d][%d]: " % (i_scatterer, i_xyz),
                      fast_gradie, match)
                print()
            assert not match.is_bad
    sys.stdout.flush()
def site(structure_ideal, d_min, f_obs, verbose=0):
  sh = shifted_site(f_obs, structure_ideal, 0, 0, 0.01)
  if (0 or verbose):
    print "site"
    sh.structure_shifted.show_summary().show_scatterers()
    print
  ls = xray.targets_least_squares_residual(
    f_obs.data(), sh.f_calc.data(), True, 1)
  gradient_flags = randomize_gradient_flags(
    xray.structure_factors.gradient_flags(site=True),
    f_obs.anomalous_flag())
  xray.set_scatterer_grad_flags(scatterers = sh.structure_shifted.scatterers(),
                                site       = gradient_flags.site,
                                u_iso      = gradient_flags.u_iso,
                                u_aniso    = gradient_flags.u_aniso,
                                occupancy  = gradient_flags.occupancy,
                                fp         = gradient_flags.fp,
                                fdp        = gradient_flags.fdp)
  sfd = xray.structure_factors.gradients_direct(
    xray_structure=sh.structure_shifted,
    u_iso_refinable_params=None,
    miller_set=f_obs,
    d_target_d_f_calc=ls.derivatives(),
    n_parameters=0)
  re = resampling(miller_set=f_obs)
  map0 = re(
    xray_structure=sh.structure_shifted,
    u_iso_refinable_params=None,
    dp=miller.array(miller_set=f_obs, data=ls.derivatives()),
    n_parameters=0,
    verbose=verbose)
  sfd_d_target_d_site_cart = sfd.d_target_d_site_cart()
  top_gradient = None
  for i_scatterer,scatterer in enumerate(sh.structure_shifted.scatterers()):
    for i_xyz in (0,1,2):
      direct_summ = sfd_d_target_d_site_cart[i_scatterer][i_xyz]
      if (top_gradient is None): top_gradient = direct_summ
      fast_gradie = map0.d_target_d_site_cart()[i_scatterer][i_xyz]
      match = judge(scatterer, "site", direct_summ, fast_gradie, top_gradient)
      if (0 or verbose):
        print "direct summ[%d][%d]: " % (i_scatterer,i_xyz), direct_summ
        print "fast gradie[%d][%d]: " % (i_scatterer,i_xyz), fast_gradie, match
        print
      assert not match.is_bad
  sys.stdout.flush()
def u_star(structure_ideal, d_min, f_obs, verbose=0):
  sh = shifted_u_star(f_obs, structure_ideal, 0, 0, 0.0001)
  if (0 or verbose):
    print "u_star"
    sh.structure_shifted.show_summary().show_scatterers()
    print
  ls = xray.targets_least_squares_residual(
    f_obs.data(), sh.f_calc.data(), True, 1)
  gradient_flags = randomize_gradient_flags(
    xray.structure_factors.gradient_flags(u_aniso=True),
    f_obs.anomalous_flag())
  xray.set_scatterer_grad_flags(scatterers = sh.structure_shifted.scatterers(),
                                site       = gradient_flags.site,
                                u_iso      = gradient_flags.u_iso,
                                u_aniso    = gradient_flags.u_aniso,
                                occupancy  = gradient_flags.occupancy,
                                fp         = gradient_flags.fp,
                                fdp        = gradient_flags.fdp)
  grad_flags_counts = xray.scatterer_grad_flags_counts(sh.structure_shifted.scatterers())
  if(grad_flags_counts.n_parameters() > 0):
     if (0):
       print "u_aniso"
       print "gradient_flags.site      ", gradient_flags.site
       print "gradient_flags.u_iso     ", gradient_flags.u_iso
       print "gradient_flags.u_aniso   ", gradient_flags.u_aniso
       print "gradient_flags.occupancy ", gradient_flags.occupancy
       print "gradient_flags.fp        ", gradient_flags.fp
       print "gradient_flags.fdp       ", gradient_flags.fdp
       cntr_use_u_iso = 0
       cntr_use_u_aniso = 0
       cntr_grad_u_iso = 0
       cntr_grad_u_aniso = 0
       for scatterer in sh.structure_shifted.scatterers():
         if (scatterer.flags.use_u_iso()):  cntr_use_u_iso += 1
         if (scatterer.flags.use_u_aniso()):  cntr_use_u_aniso += 1
         if (scatterer.flags.grad_u_iso()):  cntr_grad_u_iso += 1
         if (scatterer.flags.grad_u_aniso()):  cntr_grad_u_aniso += 1
       print "use_u_iso                ", cntr_use_u_iso,cntr_grad_u_iso
       print "use_u_aniso              ", cntr_use_u_aniso,cntr_grad_u_aniso
     sfd = xray.structure_factors.gradients_direct(
       xray_structure=sh.structure_shifted,
       u_iso_refinable_params=None,
       miller_set=f_obs,
       d_target_d_f_calc=ls.derivatives(),
       n_parameters= 0
       )
     re = resampling(miller_set=f_obs)
     map0 = re(
       xray_structure=sh.structure_shifted,
       u_iso_refinable_params=None,
       dp=miller.array(miller_set=f_obs, data=ls.derivatives()),
       n_parameters= 0,
       verbose=verbose)

     grad_flags_counts = xray.scatterer_grad_flags_counts(sh.structure_shifted.scatterers())
     if(grad_flags_counts.u_aniso):
        sfd_d_target_d_u_cart = sfd.d_target_d_u_cart()
        map0_d_target_d_u_cart = map0.d_target_d_u_cart()
     top_gradient = None
     gradients_1 = []
     for i_scatterer,scatterer in enumerate(sh.structure_shifted.scatterers()):
       if(scatterer.flags.use_u_iso()):   parameter_name = "u_iso"
       if(scatterer.flags.use_u_aniso()): parameter_name = "u_star"
       if(parameter_name == "u_iso" and scatterer.flags.grad_u_iso()):
          direct_summ = sfd.d_target_d_u_iso()[i_scatterer]
          if (top_gradient is None): top_gradient = direct_summ
          fast_gradie = map0.d_target_d_u_iso()[i_scatterer]
          sys.stdout.flush()
          gradients_1.append([direct_summ, fast_gradie])
          match = judge(scatterer, parameter_name, direct_summ, fast_gradie,
                                                                  top_gradient)
          if (0 or verbose):
            print "direct summ[%d]: " % i_scatterer, direct_summ
            print "fast gradie[%d]: " % i_scatterer, fast_gradie, match
            print
          assert not match.is_bad
       if parameter_name == "u_star" and scatterer.flags.grad_u_aniso():
        sfd_star = sfd.d_target_d_u_star()[i_scatterer]
        sfd_cart = adptbx.grad_u_star_as_u_cart(
          structure_ideal.unit_cell(), sfd_star)
        assert approx_equal(
          sfd_star,
          adptbx.grad_u_cart_as_u_star(structure_ideal.unit_cell(), sfd_cart))
        for ij in xrange(6):
          direct_summ = sfd_d_target_d_u_cart[i_scatterer][ij]
          if (top_gradient is None): top_gradient = direct_summ
          fast_gradie = map0_d_target_d_u_cart[i_scatterer][ij]
          gradients_1.append([direct_summ, fast_gradie])
          match =judge(scatterer,"u_star",direct_summ,fast_gradie,top_gradient)
          if (0 or verbose or match.is_bad):
            print "direct summ[%d][%d]: " % (i_scatterer, ij), direct_summ
            print "fast gradie[%d][%d]: " % (i_scatterer, ij),fast_gradie,match
            print
          assert not match.is_bad
     # Making sure that gradients_1 = gradients_2
     for i_scatterer,scatterer in enumerate(sh.structure_shifted.scatterers()):
         if(not scatterer.flags.use_u_iso()):
            scatterer.u_iso = -12345.0
         if(not scatterer.flags.use_u_aniso()):
            scatterer.u_star =(-999.,-999.,-999.,-999.,-999.,-999.)
     sfd = xray.structure_factors.gradients_direct(
       xray_structure=sh.structure_shifted,
       u_iso_refinable_params=None,
       miller_set=f_obs,
       d_target_d_f_calc=ls.derivatives(),
       n_parameters= 0
       )
     re = resampling(miller_set=f_obs)
     map0 = re(
       xray_structure=sh.structure_shifted,
       u_iso_refinable_params=None,
       dp=miller.array(miller_set=f_obs, data=ls.derivatives()),
       n_parameters= 0,
       verbose=verbose)

     grad_flags_counts = \
            xray.scatterer_grad_flags_counts(sh.structure_shifted.scatterers())
     if(grad_flags_counts.u_aniso):
        sfd_d_target_d_u_cart = sfd.d_target_d_u_cart()
        map0_d_target_d_u_cart = map0.d_target_d_u_cart()
     gradients_2 = []
     for i_scatterer,scatterer in enumerate(sh.structure_shifted.scatterers()):
       if(scatterer.flags.use_u_iso()):   parameter_name = "u_iso"
       if(scatterer.flags.use_u_aniso()): parameter_name = "u_star"
       if(parameter_name == "u_iso" and scatterer.flags.grad_u_iso()):
          direct_summ = sfd.d_target_d_u_iso()[i_scatterer]
          fast_gradie = map0.d_target_d_u_iso()[i_scatterer]
          gradients_2.append([direct_summ, fast_gradie])
       if parameter_name == "u_star" and scatterer.flags.grad_u_aniso():
        sfd_star = sfd.d_target_d_u_star()[i_scatterer]
        sfd_cart = adptbx.grad_u_star_as_u_cart(
          structure_ideal.unit_cell(), sfd_star)
        assert approx_equal(
          sfd_star,
          adptbx.grad_u_cart_as_u_star(structure_ideal.unit_cell(), sfd_cart))
        for ij in xrange(6):
          direct_summ = sfd_d_target_d_u_cart[i_scatterer][ij]
          fast_gradie = map0_d_target_d_u_cart[i_scatterer][ij]
          gradients_2.append([direct_summ, fast_gradie])
     for g1,g2 in zip(gradients_1, gradients_2):
       assert approx_equal(g1, g2)
     sys.stdout.flush()
def timings(structure, d_min, fft_only=False,
            wing_cutoff_reference=1.e-6,
            wing_cutoff_others=1.e-3):
  structure_ng = structure.deep_copy_scatterers()
  structure_5g = structure.deep_copy_scatterers()
  structure_4g = structure.deep_copy_scatterers()
  structure_2g = structure.deep_copy_scatterers()
  structure_1g = structure.deep_copy_scatterers()
  structure_ng.scattering_type_registry(d_min=d_min, table="n_gaussian")
  structure_5g.scattering_type_registry(table="wk1995")
  structure_4g.scattering_type_registry(table="it1992")
  custom_dict = {}
  custom_dict.update(eltbx.xray_scattering.two_gaussian_agarwal_isaacs.table)
  structure_2g.scattering_type_registry(custom_dict=custom_dict)
  custom_dict.update(eltbx.xray_scattering.one_gaussian_agarwal_1978.table)
  structure_1g.scattering_type_registry(custom_dict=custom_dict)
  miller_set = miller.build_set(
    crystal_symmetry=structure,
    d_min=d_min,
    anomalous_flag=False)
  miller_set.show_summary()
  print "d_min:", d_min
  if (fft_only):
    timer = user_plus_sys_time()
    f_calc_reference = xray.structure_factors.from_scatterers(
      miller_set=miller_set,
      wing_cutoff=wing_cutoff_reference,
      exp_table_one_over_step_size=0)(
        xray_structure=structure,
        miller_set=miller_set,
        algorithm="fft").f_calc().data()
    print "fft exp function wing_cutoff=%3.1e: %.2f seconds" % (
      wing_cutoff_reference, timer.elapsed())
  else:
    timer = user_plus_sys_time()
    f_calc_reference = xray.structure_factors_simple(
      structure_5g.unit_cell(),
      structure_5g.space_group(),
      miller_set.indices(),
      structure_5g.scatterers(),
      structure_5g.scattering_type_registry()).f_calc()
    print "direct simple: %.2f seconds" % timer.elapsed()
  f_calc_reference = flex.abs(f_calc_reference)
  print "wing_cutoff for following fft calculations: %3.1e"%wing_cutoff_others
  for structure in (structure_ng, structure_5g, structure_4g,
                    structure_2g, structure_1g):
    structure.scattering_type_registry().show_summary()
    if (not fft_only):
      for calc_type,cos_sin_flag in (("direct cos+sin function:",False),
                                     ("direct cos+sin table:",True)):
        timer = user_plus_sys_time()
        f_calc = miller_set.structure_factors_from_scatterers(
          xray_structure=structure,
          algorithm="direct",
          cos_sin_table=cos_sin_flag).f_calc()
        print "  %-24s %.2f seconds," % (calc_type, timer.elapsed()),
        ls = xray.targets_least_squares_residual(
          f_calc_reference, f_calc.data(), False, 1)
        print "r-factor: %.6f" % ls.target()
    for calc_type,exp_table_one_over_step_size in (("fft exp function:",0),
                                                   ("fft exp table:",-100)):
      timer = user_plus_sys_time()
      f_calc = xray.structure_factors.from_scatterers(
        miller_set=miller_set,
        wing_cutoff=wing_cutoff_others,
        exp_table_one_over_step_size=exp_table_one_over_step_size)(
          xray_structure=structure,
          miller_set=miller_set,
          algorithm="fft").f_calc()
      print "  %-24s %.2f seconds," % (calc_type, timer.elapsed()),
      ls = xray.targets_least_squares_residual(
        f_calc_reference, f_calc.data(), False, 1)
      print "r-factor: %.6f" % ls.target()
  print
Пример #8
0
def u_iso(structure_ideal, d_min, f_obs, tan_u_iso, verbose=0):
    sh = shifted_u_iso(f_obs, structure_ideal, 0, 0.05)
    if (0 or verbose):
        print("u_iso")
        sh.structure_shifted.show_summary().show_scatterers()
        print()
    ls = xray.targets_least_squares_residual(f_obs.data(), sh.f_calc.data(),
                                             True, 1)
    gradient_flags = randomize_gradient_flags(
        xray.structure_factors.gradient_flags(u_iso=True),
        f_obs.anomalous_flag())
    if (tan_u_iso):
        u_iso_refinable_params = flex.double()
    else:
        u_iso_refinable_params = None
    for scatterer in sh.structure_shifted.scatterers():
        scatterer.flags.set_grad_site(gradient_flags.site)
        scatterer.flags.set_grad_u_iso(gradient_flags.u_iso)
        scatterer.flags.set_grad_u_aniso(gradient_flags.u_aniso)
        scatterer.flags.set_grad_occupancy(gradient_flags.occupancy)
        scatterer.flags.set_grad_fp(gradient_flags.fp)
        scatterer.flags.set_grad_fdp(gradient_flags.fdp)
        if (tan_u_iso):
            scatterer.flags.set_tan_u_iso(True)
            param = random.randint(90, 120)
            scatterer.flags.param = param
            value = math.tan(scatterer.u_iso * math.pi / adptbx.b_as_u(param) -
                             math.pi / 2)
            u_iso_refinable_params.append(value)
    if (0):
        print("u_iso")
        print("gradient_flags.site      ", gradient_flags.site)
        print("gradient_flags.u_iso     ", gradient_flags.u_iso)
        print("gradient_flags.u_aniso   ", gradient_flags.u_aniso)
        print("gradient_flags.occupancy ", gradient_flags.occupancy)
        print("gradient_flags.fp        ", gradient_flags.fp)
        print("gradient_flags.fdp       ", gradient_flags.fdp)
        cntr_use_u_iso = 0
        cntr_use_u_aniso = 0
        cntr_grad_u_iso = 0
        cntr_grad_u_aniso = 0
        for scatterer in sh.structure_shifted.scatterers():
            if (scatterer.flags.use_u_iso()): cntr_use_u_iso += 1
            if (scatterer.flags.use_u_aniso()): cntr_use_u_aniso += 1
            if (scatterer.flags.grad_u_iso()): cntr_grad_u_iso += 1
            if (scatterer.flags.grad_u_aniso()): cntr_grad_u_aniso += 1
        print("use_u_iso                ", cntr_use_u_iso, cntr_grad_u_iso)
        print("use_u_aniso              ", cntr_use_u_aniso, cntr_grad_u_aniso)
    grad_flags_counts = \
              xray.scatterer_grad_flags_counts(sh.structure_shifted.scatterers())
    if (grad_flags_counts.n_parameters() > 0):
        sfd = xray.structure_factors.gradients_direct(
            xray_structure=sh.structure_shifted,
            u_iso_refinable_params=u_iso_refinable_params,
            miller_set=f_obs,
            d_target_d_f_calc=ls.derivatives(),
            n_parameters=0)
        re = resampling(miller_set=f_obs)
        map0 = re(xray_structure=sh.structure_shifted,
                  u_iso_refinable_params=u_iso_refinable_params,
                  dp=miller.array(miller_set=f_obs, data=ls.derivatives()),
                  n_parameters=0,
                  verbose=verbose)
        if (grad_flags_counts.u_aniso > 0):
            sfd_d_target_d_u_cart = sfd.d_target_d_u_cart()
            map0_d_target_d_u_cart = map0.d_target_d_u_cart()
        top_gradient = None
        gradients_1 = []
        for i_scatterer, scatterer in enumerate(
                sh.structure_shifted.scatterers()):
            if (0):
                print("i_scatterer= ", i_scatterer,scatterer.flags.use_u_iso(),\
                  scatterer.flags.grad_u_iso(), scatterer.flags.use_u_aniso(),\
                  scatterer.flags.grad_u_aniso(), scatterer.u_iso, scatterer.u_star)
            if (scatterer.flags.use_u_iso()): parameter_name = "u_iso"
            if (scatterer.flags.use_u_aniso()): parameter_name = "u_star"
            if (parameter_name == "u_iso" and scatterer.flags.grad_u_iso()
                    and scatterer.flags.use_u_iso()):
                direct_summ = sfd.d_target_d_u_iso()[i_scatterer]
                if (top_gradient is None): top_gradient = direct_summ
                fast_gradie = map0.d_target_d_u_iso()[i_scatterer]
                sys.stdout.flush()
                gradients_1.append([direct_summ, fast_gradie])
                match = judge(scatterer, parameter_name, direct_summ,
                              fast_gradie, top_gradient)
                if (0 or verbose):
                    print("direct summ[%d]: " % i_scatterer, direct_summ)
                    print("fast gradie[%d]: " % i_scatterer, fast_gradie,
                          match)
                    print()
                assert not match.is_bad
            if (parameter_name == "u_star" and scatterer.flags.grad_u_aniso()
                    and scatterer.flags.use_u_aniso()):
                sfd_star = sfd.d_target_d_u_star()[i_scatterer]
                sfd_cart = adptbx.grad_u_star_as_u_cart(
                    structure_ideal.unit_cell(), sfd_star)
                assert approx_equal(
                    sfd_star,
                    adptbx.grad_u_cart_as_u_star(structure_ideal.unit_cell(),
                                                 sfd_cart))
                for ij in range(6):
                    direct_summ = sfd_d_target_d_u_cart[i_scatterer][ij]
                    if (top_gradient is None): top_gradient = direct_summ
                    fast_gradie = map0_d_target_d_u_cart[i_scatterer][ij]
                    gradients_1.append([direct_summ, fast_gradie])
                    match = judge(scatterer, "u_star", direct_summ,
                                  fast_gradie, top_gradient)
                    if (0 or verbose or match.is_bad):
                        print("direct summ[%d][%d]: " % (i_scatterer, ij),
                              direct_summ)
                        print("fast gradie[%d][%d]: " % (i_scatterer, ij),
                              fast_gradie, match)
                        print()
                    assert not match.is_bad
        # Making sure that gradients_1 = gradients_2
        for i_scatterer, scatterer in enumerate(
                sh.structure_shifted.scatterers()):
            if (not scatterer.flags.use_u_iso()):
                scatterer.u_iso = -12345.0
            if (not scatterer.flags.use_u_aniso()):
                scatterer.u_star = (-999., -999., -999., -999., -999., -999.)
        sfd = xray.structure_factors.gradients_direct(
            xray_structure=sh.structure_shifted,
            u_iso_refinable_params=u_iso_refinable_params,
            miller_set=f_obs,
            d_target_d_f_calc=ls.derivatives(),
            n_parameters=0)
        re = resampling(miller_set=f_obs)
        map0 = re(xray_structure=sh.structure_shifted,
                  u_iso_refinable_params=u_iso_refinable_params,
                  dp=miller.array(miller_set=f_obs, data=ls.derivatives()),
                  n_parameters=0,
                  verbose=verbose)
        grad_flags_counts = \
               xray.scatterer_grad_flags_counts(sh.structure_shifted.scatterers())
        if (grad_flags_counts.u_aniso):
            sfd_d_target_d_u_cart = sfd.d_target_d_u_cart()
            map0_d_target_d_u_cart = map0.d_target_d_u_cart()
        gradients_2 = []
        for i_scatterer, scatterer in enumerate(
                sh.structure_shifted.scatterers()):
            if (scatterer.flags.use_u_iso()): parameter_name = "u_iso"
            if (scatterer.flags.use_u_aniso()): parameter_name = "u_star"
            if (parameter_name == "u_iso" and scatterer.flags.grad_u_iso()
                    and scatterer.flags.use_u_iso()):
                direct_summ = sfd.d_target_d_u_iso()[i_scatterer]
                fast_gradie = map0.d_target_d_u_iso()[i_scatterer]
                gradients_2.append([direct_summ, fast_gradie])
            if (parameter_name == "u_star" and scatterer.flags.grad_u_aniso()
                    and scatterer.flags.use_u_aniso()):
                sfd_star = sfd.d_target_d_u_star()[i_scatterer]
                sfd_cart = adptbx.grad_u_star_as_u_cart(
                    structure_ideal.unit_cell(), sfd_star)
                assert approx_equal(
                    sfd_star,
                    adptbx.grad_u_cart_as_u_star(structure_ideal.unit_cell(),
                                                 sfd_cart))
                for ij in range(6):
                    direct_summ = sfd_d_target_d_u_cart[i_scatterer][ij]
                    fast_gradie = map0_d_target_d_u_cart[i_scatterer][ij]
                    gradients_2.append([direct_summ, fast_gradie])
        for g1, g2 in zip(gradients_1, gradients_2):
            assert approx_equal(g1, g2)
        sys.stdout.flush()
def timings(structure,
            d_min,
            fft_only=False,
            wing_cutoff_reference=1.e-6,
            wing_cutoff_others=1.e-3):
    structure_ng = structure.deep_copy_scatterers()
    structure_5g = structure.deep_copy_scatterers()
    structure_4g = structure.deep_copy_scatterers()
    structure_2g = structure.deep_copy_scatterers()
    structure_1g = structure.deep_copy_scatterers()
    structure_ng.scattering_type_registry(d_min=d_min, table="n_gaussian")
    structure_5g.scattering_type_registry(table="wk1995")
    structure_4g.scattering_type_registry(table="it1992")
    custom_dict = {}
    custom_dict.update(eltbx.xray_scattering.two_gaussian_agarwal_isaacs.table)
    structure_2g.scattering_type_registry(custom_dict=custom_dict)
    custom_dict.update(eltbx.xray_scattering.one_gaussian_agarwal_1978.table)
    structure_1g.scattering_type_registry(custom_dict=custom_dict)
    miller_set = miller.build_set(crystal_symmetry=structure,
                                  d_min=d_min,
                                  anomalous_flag=False)
    miller_set.show_summary()
    print("d_min:", d_min)
    if (fft_only):
        timer = user_plus_sys_time()
        f_calc_reference = xray.structure_factors.from_scatterers(
            miller_set=miller_set,
            wing_cutoff=wing_cutoff_reference,
            exp_table_one_over_step_size=0)(xray_structure=structure,
                                            miller_set=miller_set,
                                            algorithm="fft").f_calc().data()
        print("fft exp function wing_cutoff=%3.1e: %.2f seconds" %
              (wing_cutoff_reference, timer.elapsed()))
    else:
        timer = user_plus_sys_time()
        f_calc_reference = xray.structure_factors_simple(
            structure_5g.unit_cell(), structure_5g.space_group(),
            miller_set.indices(), structure_5g.scatterers(),
            structure_5g.scattering_type_registry()).f_calc()
        print("direct simple: %.2f seconds" % timer.elapsed())
    f_calc_reference = flex.abs(f_calc_reference)
    print("wing_cutoff for following fft calculations: %3.1e" %
          wing_cutoff_others)
    for structure in (structure_ng, structure_5g, structure_4g, structure_2g,
                      structure_1g):
        structure.scattering_type_registry().show_summary()
        if (not fft_only):
            for calc_type, cos_sin_flag in (("direct cos+sin function:",
                                             False), ("direct cos+sin table:",
                                                      True)):
                timer = user_plus_sys_time()
                f_calc = miller_set.structure_factors_from_scatterers(
                    xray_structure=structure,
                    algorithm="direct",
                    cos_sin_table=cos_sin_flag).f_calc()
                print("  %-24s %.2f seconds," % (calc_type, timer.elapsed()),
                      end=' ')
                ls = xray.targets_least_squares_residual(
                    f_calc_reference, f_calc.data(), False, 1)
                print("r-factor: %.6f" % ls.target())
        for calc_type, exp_table_one_over_step_size in (("fft exp function:",
                                                         0), ("fft exp table:",
                                                              -100)):
            timer = user_plus_sys_time()
            f_calc = xray.structure_factors.from_scatterers(
                miller_set=miller_set,
                wing_cutoff=wing_cutoff_others,
                exp_table_one_over_step_size=exp_table_one_over_step_size)(
                    xray_structure=structure,
                    miller_set=miller_set,
                    algorithm="fft").f_calc()
            print("  %-24s %.2f seconds," % (calc_type, timer.elapsed()),
                  end=' ')
            ls = xray.targets_least_squares_residual(f_calc_reference,
                                                     f_calc.data(), False, 1)
            print("r-factor: %.6f" % ls.target())
    print()