Ejemplo n.º 1
0
void Fragment::set_residue_indexes(kernel::Model *m, kernel::ParticleIndex pi,
                                   Ints o) {
  if (o.empty()) {
    set_residue_indexes(m, pi, IntPairs());
    return;
  }
  std::sort(o.begin(), o.end());
  o.erase(std::unique(o.begin(), o.end()), o.end());
  IntPairs pairs;
  int begin = 0;
  for (unsigned int i = 1; i < o.size(); ++i) {
    if (o[i] != o[i - 1] + 1) {
      pairs.push_back(IntPair(o[begin], o[i - 1] + 1));
      begin = i;
    }
  }
  pairs.push_back(IntPair(o[begin], o.back() + 1));
  set_residue_indexes(m, pi, pairs);
  using IMP::operator<<;
  IMP_IF_CHECK(USAGE) {
    for (unsigned int i = 0; i < o.size(); ++i) {
      IMP_INTERNAL_CHECK(Fragment(m, pi).get_contains_residue(o[i]),
                         "Residue index not found after addition: "
                             << o << " became " << pairs);
    }
  }
}
Ejemplo n.º 2
0
IntPairs Fragment::get_residue_index_ranges() const {
  if (!get_model()->get_has_attribute(get_begins_key(), get_particle_index())) {
    return IntPairs();
  }
  Ints begins =
      get_model()->get_attribute(get_begins_key(), get_particle_index());
  Ints ends = get_model()->get_attribute(get_ends_key(), get_particle_index());
  IMP_INTERNAL_CHECK(begins.size() == ends.size(),
                     "The fragment residues are corrupted.");
  IntPairs ret(begins.size());
  for (unsigned int i = 0; i < ret.size(); ++i) {
    ret[i] = IntPair(begins[i], ends[i]);
  }
  return ret;
}
/// For algorithm details, see http://wiki.openstreetmap.org/wiki/Relation:multipolygon/Algorithm
void MultipolygonProcessor::process() {
  bool allClosed = true;
  // NOTE do not count multipolygon tag itself
  bool hasNoTags = relation_.tags.size() < 2;
  Ints outerIndecies;
  Ints innerIndecies;
  CoordinateSequences sequences;
  for (const auto &member : members_) {

    if (member.type!="w")
      continue;

    Coordinates coordinates;
    auto wayPair = context_.wayMap.find(member.refId);
    if (wayPair!=context_.wayMap.end()) {
      coordinates = wayPair->second->coordinates;
    } else {
      auto areaPair = context_.areaMap.find(member.refId);
      if (areaPair!=context_.areaMap.end()) {
        coordinates = areaPair->second->coordinates;

        // NOTE make coordinates to be closed ring
        coordinates.push_back(coordinates[0]);

        // NOTE merge tags to relation
        // hasNoTags prevents the case where relation has members with their own tags
        // which should be processed independently (geometry reusage)
        if (member.role=="outer" && hasNoTags)
          mergeTags(areaPair->second->tags);
      } else {
        auto relationPair = context_.relationMap.find(member.refId);
        if (relationPair==context_.relationMap.end())
          return; //  NOTE cannot fill relation: incomplete data

        resolve_(*relationPair->second);
      }
    }

    if (coordinates.empty())
      continue;

    if (member.role=="outer")
      outerIndecies.push_back(static_cast<int>(sequences.size()));
    else if (member.role=="inner")
      innerIndecies.push_back(static_cast<int>(sequences.size()));
    else
      continue;

    auto sequence = std::make_shared<CoordinateSequence>(member.refId, coordinates);
    if (!sequence->isClosed())
      allClosed = false;

    sequences.push_back(sequence);
  }

  if (outerIndecies.size()==1 && allClosed)
    simpleCase(sequences, outerIndecies, innerIndecies);
  else
    complexCase(sequences);
}
Ejemplo n.º 4
0
void AnchorsData::set_secondary_structure_probabilities(
    const Particles &ssres_ps, const Ints &indices) {

  IMP_USAGE_CHECK(secondary_structure_ps_.size() == points_.size(),
                  "Secondary structure has not been set up, "
                  "run AnchorsData::setup_secondary_structure() first");
  int anum;
  for (int ssnum = 0; ssnum < (int)ssres_ps.size(); ssnum++) {
    IMP_USAGE_CHECK(
        atom::SecondaryStructureResidue::get_is_setup(ssres_ps[ssnum]),
        "SSE Particles must be decorated as"
        "SecondaryStructureResidues");
    if (indices.size() == 0)
      anum = ssnum;
    else
      anum = indices[ssnum];
    atom::SecondaryStructureResidue(secondary_structure_ps_[anum])
        .set_prob_helix(
             atom::SecondaryStructureResidue(ssres_ps[ssnum]).get_prob_helix());
    atom::SecondaryStructureResidue(secondary_structure_ps_[anum])
        .set_prob_strand(atom::SecondaryStructureResidue(ssres_ps[ssnum])
                             .get_prob_strand());
    atom::SecondaryStructureResidue(secondary_structure_ps_[anum])
        .set_prob_coil(
             atom::SecondaryStructureResidue(ssres_ps[ssnum]).get_prob_coil());
  }
}
Ejemplo n.º 5
0
void KMCentersTree::skeleton_tree(const Ints &p_id,
  KMPoint *bb_lo,KMPoint *bb_hi) {
  //TODO: where do get n from ?
  IMP_INTERNAL_CHECK(data_points_ != nullptr,
                     "Points must be supplied to construct tree.");
  if (p_id.size() == 0) {
    for (int i = 0; i < data_points_->get_number_of_points(); i++)
      p_id_.push_back(i);
  }
  else {
    for (int i = 0; i < data_points_->get_number_of_points(); i++)
      p_id_.push_back(p_id[i]);
  }
  if (bb_lo == nullptr || bb_hi == nullptr) {
    bnd_box_ = bounding_rectangle(0,data_points_->get_number_of_points()-1);;
  }
  // if points are provided, use it
  if (bb_lo != nullptr) {
    copy_point(bb_lo,bnd_box_->get_point(0));
  }
  if (bb_hi != nullptr) {
    copy_point(bb_hi,bnd_box_->get_point(1));
  }
  root_ = nullptr;
}
Ejemplo n.º 6
0
void KMCentersNodeSplit::get_neighbors(const Ints &cands, KMPointArray *sums,
                                       KMPoint *sum_sqs, Ints *weights) {
  if (cands.size() == 1) {
    IMP_LOG_VERBOSE("KMCentersNodeSplit::get_neighbors the data points are"
                    << " associated to center : " << cands[0] << std::endl);
    // post points as neighbors
    post_neighbor(sums, sum_sqs, weights, cands[0]);
  }
      // get cloest candidate to the box represented by the node
      else {
    Ints new_cands;
    IMP_LOG_VERBOSE(
        "KMCentersNodeSplit::get_neighbors compute close centers for node:\n");
    IMP_LOG_WRITE(VERBOSE, show(IMP_STREAM));
    compute_close_centers(cands, &new_cands);
    for (unsigned int i = 0; i < new_cands.size(); i++) {
      IMP_LOG_VERBOSE(new_cands[i] << "  | ");
    }
    IMP_LOG_VERBOSE("\nKMCentersNodeSplit::get_neighbors call left child with "
                    << new_cands.size() << " candidates\n");
    children_[0]->get_neighbors(new_cands, sums, sum_sqs, weights);
    IMP_LOG_VERBOSE("KMCentersNodeSplit::get_neighbors call right child with "
                    << new_cands.size() << " candidates\n");
    children_[1]->get_neighbors(new_cands, sums, sum_sqs, weights);
  }
}
Ejemplo n.º 7
0
FrameHandles FrameHandle::get_children() const {
  Ints children = get_shared_data()->get_children(get_frame_id());
  FrameHandles ret(children.size());
  for (unsigned int i = 0; i < ret.size(); ++i) {
    ret[i] = FrameHandle(children[i], get_shared_data());
  }
  return ret;
}
Ejemplo n.º 8
0
bool PymolWriter::handle_surface(SurfaceMeshGeometry *g, Color color,
                                 std::string name) {
  setup(name, TRIANGLES);
  if (!open_type_) {
    get_stream() << "BEGIN, TRIANGLES, ";
    open_type_ = TRIANGLES;
  }
  Ints triangles = internal::get_triangles(g);
  algebra::Vector3Ds normals =
      internal::get_normals(triangles, g->get_vertexes());
  IMP_INTERNAL_CHECK(triangles.size() % 3 == 0,
                     "The returned triangles aren't triangles");
  for (unsigned int i = 0; i < triangles.size() / 3; ++i) {
    write_triangle(triangles.begin() + 3 * i, triangles.begin() + 3 * i + 3,
                   g->get_vertexes(), normals, color, get_stream());
  }
  return true;
}
Ejemplo n.º 9
0
// see http://wiki.openstreetmap.org/wiki/Relation:multipolygon/Algorithm
void MultipolygonProcessor::process()
{
    bool allClosed = true;

    Ints outerIndecies;
    Ints innerIndecies;
    CoordinateSequences sequences;
    for (const auto& member : members_) {

        if (member.type != "way") 
            continue;

        Coordinates coordinates;
        auto wayPair = context_.wayMap.find(member.refId);
        if (wayPair != context_.wayMap.end()) {
            coordinates = wayPair->second->coordinates;
        }
        else {
            auto areaPair = context_.areaMap.find(member.refId);
            if (areaPair != context_.areaMap.end()) {
                coordinates = areaPair->second->coordinates;
                // NOTE merge tags to relation
                if (member.role == "outer")
                    mergeTags(areaPair->second->tags);
            }
            else {
                auto relationPair = context_.relationMap.find(member.refId);
                if (relationPair == context_.relationMap.end())
                    return; //  NOTE cannot fill relation: incomplete data

                resolve_(*relationPair->second);
            }
        }

        if (coordinates.empty()) 
            continue;

        if (member.role == "outer")
            outerIndecies.push_back(static_cast<int>(sequences.size()));
        else if (member.role == "inner")
            innerIndecies.push_back(static_cast<int>(sequences.size()));
        else
            continue;

        auto sequence = std::make_shared<CoordinateSequence>(member.refId, coordinates);
        if (!sequence->isClosed()) 
            allClosed = false;

        sequences.push_back(sequence);
    }

    if (outerIndecies.size() == 1 && allClosed)
        simpleCase(sequences, outerIndecies, innerIndecies);
    else
        complexCase(sequences);
}
Ejemplo n.º 10
0
Assignment get_merged_assignment(const Subset &s, const Assignment &ss0,
                                 const Ints &i0, const Assignment &ss1,
                                 const Ints &i1) {
  Ints ret(s.size(), -1);
  IMP_USAGE_CHECK(ss0.size() == i0.size(),
                  "The size of the subset and "
                      << "the index don't match: " << ss0.size() << " vs "
                      << i0.size());
  IMP_USAGE_CHECK(ss1.size() == i1.size(),
                  "The size of the subset and "
                      << "the index don't match: " << ss1.size() << " vs "
                      << i1.size());
  for (unsigned int i = 0; i < i0.size(); ++i) {
    ret[i0[i]] = ss0[i];
  }
  for (unsigned int i = 0; i < i1.size(); ++i) {
    ret[i1[i]] = ss1[i];
  }
  IMP_IF_CHECK(USAGE) {
    for (unsigned int i = 0; i < ret.size(); ++i) {
      IMP_USAGE_CHECK(ret[i] >= 0, "Not all set");
    }
  }
  return Assignment(ret);
}
Ejemplo n.º 11
0
void KMCentersNodeSplit::get_assignments(const Ints &cands,
                                         Ints &close_center) {
  if (cands.size() == 1) {
    children_[0]->get_assignments(cands, close_center);
    children_[1]->get_assignments(cands, close_center);
  } else {  // get closest cand to box
    Ints new_cands;
    compute_close_centers(cands, &new_cands);
    // apply to children
    children_[0]->get_assignments(new_cands, close_center);
    children_[1]->get_assignments(new_cands, close_center);
  }
}
Ejemplo n.º 12
0
NNGraph MSConnectivityScore::build_subgraph_from_assignment(
    NNGraph &G, Assignment const &assignment) const {
  unsigned int num_particles = restraint_.particle_matrix_.size();
  Ints vertices;
  for (unsigned int i = 0; i < assignment.size(); ++i)
    if (!assignment[i].empty()) {
      Ints const &conf = assignment[i].get_tuple();
      for (unsigned int j = 0; j < conf.size(); ++j)
        vertices.push_back(conf[j]);
    }
  boost::property_map<NNGraph, boost::vertex_name_t>::type vertex_id =
      boost::get(boost::vertex_name, G);
  boost::property_map<NNGraph, boost::edge_weight_t>::type dist =
      boost::get(boost::edge_weight, G);
  NNGraph ng(vertices.size());
  boost::property_map<NNGraph, boost::vertex_name_t>::type new_vertex_id =
      boost::get(boost::vertex_name, ng);
  boost::property_map<NNGraph, boost::edge_weight_t>::type new_dist =
      boost::get(boost::edge_weight, ng);
  for (unsigned int i = 0; i < vertices.size(); ++i)
    boost::put(new_vertex_id, i, vertices[i]);
  Ints vertex_id_to_idx(num_particles, -1);
  for (unsigned int i = 0; i < vertices.size(); ++i)
    vertex_id_to_idx[vertices[i]] = i;
  NNGraph::edge_iterator e, end;
  for (boost::tie(e, end) = edges(G); e != end; ++e) {
    unsigned int source_id = boost::get(vertex_id, source(*e, G));
    unsigned int dest_id = boost::get(vertex_id, target(*e, G));
    unsigned int p_src = vertex_id_to_idx[source_id];
    unsigned int p_dst = vertex_id_to_idx[dest_id];
    if (p_src == static_cast<unsigned int>(-1) ||
        p_dst == static_cast<unsigned int>(-1))
      continue;
    NNGraph::edge_descriptor ed = boost::add_edge(p_src, p_dst, ng).first;
    double d = boost::get(dist, *e);
    boost::put(new_dist, ed, d);
  }
  return ng;
}
Ejemplo n.º 13
0
algebra::Vector3Ds get_normals(const Ints &faces,
                               const algebra::Vector3Ds &vertices) {
  IMP_INTERNAL_CHECK(faces.size() % 3 == 0, "Not triangles");
  IMP_INTERNAL_CHECK(faces.size() > 0, "No faces");
  Ints count(vertices.size());
  algebra::Vector3Ds sum(vertices.size(), algebra::get_zero_vector_d<3>());
  for (unsigned int i = 0; i < faces.size() / 3; ++i) {
    algebra::Vector3D n =
        get_normal(faces.begin() + 3 * i, faces.begin() + 3 * i + 3, vertices);
    IMP_INTERNAL_CHECK(!IMP::isnan(n[0]), "Nan found");
    for (unsigned int j = 0; j < 3; ++j) {
      int v = faces[3 * i + j];
      sum[v] += n;
      count[v] += 1;
    }
  }
  for (unsigned int i = 0; i < count.size(); ++i) {
    sum[i] /= count[i];
    IMP_INTERNAL_CHECK(!IMP::isnan(sum[i][0]),
                       "Nan found at end:" << count[i] << " on " << i);
  }
  return sum;
}
Ejemplo n.º 14
0
void Changer::remainingActionsDecrement(
    Ints& actions_vect,
    int bacterium_index
) {
    bool less = bacterium_index < 0;
    bool greater = bacterium_index >= actions_vect.size();
    if (less || greater) {
        throw Exception("Changer: invalid bacterium index.");
    }
    actions_vect[bacterium_index]--;
    if (actions_vect[bacterium_index] < 0) {
        throw Exception("Changer: too many commands for one move.");
    }
}
Ejemplo n.º 15
0
domino::SubsetFilter* ExampleSubsetFilterTable::get_subset_filter(
    const domino::Subset& cur_subset,
    const domino::Subsets& prior_subsets) const {
  IMP_OBJECT_LOG;
  Ints its = get_indexes(cur_subset, prior_subsets);
  if (its.size() != ps_.size()) {
    // either the subset doesn't contain the needed particles or the prior does
    return nullptr;
  } else {
    IMP_NEW(ExampleSubsetFilter, ret, (its, max_diff_));
    // remember to release
    return ret.release();
  }
}
Ejemplo n.º 16
0
InferenceStatistics::Data InferenceStatistics::get_data(
    const Subset &, AssignmentContainer *iss) const {
  Assignments ss =
      iss->get_assignments(IntRange(0, iss->get_number_of_assignments()));
  Data ret;
  ret.size = iss->get_number_of_assignments();
  Ints sample;
  for (int i = 0; i < ret.size; ++i) {
    if (sample.size() < sample_size) {
      sample.push_back(i);
    } else {
      double prob = static_cast<double>(sample_size) / i;
      if (select_(base::random_number_generator) < prob) {
        int replace = place_(base::random_number_generator);
        sample[replace] = i;
      }
    }
  }
  ret.sample.resize(sample.size());
  for (unsigned int i = 0; i < sample.size(); ++i) {
    ret.sample[i] = iss->get_assignment(sample[i]);
  }
  return ret;
}
Ejemplo n.º 17
0
bool PymolWriter::handle_polygon(PolygonGeometry *g, Color color,
                                 std::string name) {
  setup(name, TRIANGLES);
  if (!open_type_) {
    get_stream() << "BEGIN, TRIANGLES, ";
    open_type_ = TRIANGLES;
  }
  Ints tris = internal::get_triangles(g);
  algebra::Vector3Ds normals = internal::get_normals(tris, g->get_geometry());
  for (unsigned int i = 0; i < tris.size() / 3; ++i) {
    write_triangle(tris.begin() + 3 * i, tris.begin() + 3 * i + 3,
                   g->get_geometry(), normals, color, get_stream());
  }
  return true;
}
Ejemplo n.º 18
0
void RestraintCache::save_cache(const kernel::ParticlesTemp &particle_ordering,
                                const kernel::RestraintsTemp &restraints,
                                RMF::HDF5::Group group,
                                unsigned int max_entries) {
  RMF::HDF5::FloatDataSet1Ds scores;
  RMF::HDF5::IntDataSet2Ds assignments;
  base::map<kernel::Restraint *, int> restraint_index;
  ParticleIndex particle_index = get_particle_index(particle_ordering);
  Orders orders = get_orders(known_restraints_, restraints, particle_ordering);
  // create data sets for restraints
  for (unsigned int i = 0; i < restraints.size(); ++i) {
    kernel::Restraint *r = restraints[i];
    RestraintID rid =
        get_restraint_id(particle_index, known_restraints_.find(r)->second,
                         restraint_index_.find(r)->second);
    RMF::HDF5::Group g = group.add_child_group(r->get_name());
    g.set_attribute<RMF::HDF5::IndexTraits>(
        "restraint", RMF::HDF5::Indexes(1, rid.get_restraint_index()));
    g.set_attribute<RMF::HDF5::IndexTraits>(
        "particles", RMF::HDF5::Indexes(rid.get_particle_indexes().begin(),
                                        rid.get_particle_indexes().end()));
    scores.push_back(g.add_child_data_set<RMF::HDF5::FloatTraits, 1>("scores"));
    assignments.push_back(
        g.add_child_data_set<RMF::HDF5::IntTraits, 2>("assignments"));
    restraint_index[r] = i;
  }
  // finally start saving them
  unsigned int count = 0;
  for (Cache::ContentIterator it = cache_.contents_begin();
       it != cache_.contents_end(); ++it) {
    int ri = restraint_index.find(it->key.get_restraint())->second;
    Ints ord = orders[ri].get_list_ordered(it->key.get_assignment());
    double score = it->value;
    RMF::HDF5::DataSetIndexD<2> asz = assignments[ri].get_size();
    RMF::HDF5::DataSetIndexD<1> row(asz[0]);
    asz[1] = ord.size();
    ++asz[0];
    assignments[ri].set_size(asz);
    assignments[ri].set_row(row, RMF::HDF5::Ints(ord.begin(), ord.end()));
    RMF::HDF5::DataSetIndexD<1> ssz = scores[ri].get_size();
    RMF::HDF5::DataSetIndexD<1> nsz = ssz;
    ++nsz[0];
    scores[ri].set_size(nsz);
    scores[ri].set_value(ssz, score);
    ++count;
    if (count > max_entries) break;
  }
}
Ejemplo n.º 19
0
Hierarchy create_protein(Model *m, std::string name, double resolution,
                         const Ints db) {
  Hierarchy root = Hierarchy::setup_particle(new Particle(m));
  Domain::setup_particle(root, IntRange(db.front(), db.back()));
  for (unsigned int i = 1; i < db.size(); ++i) {
    std::ostringstream oss;
    oss << name << "-" << i - 1;
    Hierarchy cur = create_protein(
        m, oss.str(), resolution, db[i] - db[i - 1], db[i - 1],
        atom::get_volume_from_mass(
            atom::get_mass_from_number_of_residues(db[i] - db[i - 1])),
        false);
    root.add_child(cur);
  }
  Molecule::setup_particle(root);
  root->set_name(name);
  return root;
}
PartitionalClustering *
RecursivePartitionalClusteringMetric::create_full_clustering(
    PartitionalClustering *center_cluster) {
  IMP::base::Vector<Ints> clusters(center_cluster->get_number_of_clusters());
  Ints reps(clusters.size());
  for (unsigned int i = 0; i < clusters.size(); ++i) {
    Ints outer = center_cluster->get_cluster(i);
    reps[i] = clustering_->get_cluster_representative(
        center_cluster->get_cluster_representative(i));
    for (unsigned int j = 0; j < outer.size(); ++j) {
      Ints inner = clustering_->get_cluster(outer[j]);
      clusters[i].insert(clusters[i].end(), inner.begin(), inner.end());
    }
  }
  IMP_NEW(internal::TrivialPartitionalClustering, ret, (clusters, reps));
  validate_partitional_clustering(ret, metric_->get_number_of_items());
  return ret.release();
}
Ejemplo n.º 21
0
bool ChimeraWriter::handle_polygon(PolygonGeometry *g, Color color,
                                   std::string name) {
  cleanup(name, false, true);
  Ints triangles = internal::get_triangles(g);
  get_stream() << "v=[";
  for (unsigned int i = 0; i < g->get_geometry().size(); ++i) {
    get_stream() << "(" << commas_io(g->get_geometry()[i]) << "), ";
  }
  get_stream() << "]\n";
  get_stream() << "vi=[";
  for (unsigned int i = 0; i < triangles.size() / 3; ++i) {
    get_stream() << "(" << triangles[3 * i] << ", " << triangles[3 * i + 1]
                 << ", " << triangles[3 * i + 2] << "), ";
  }
  get_stream() << "]\n";
  get_stream() << "m.addPiece(v, vi, (" << commas_io(color) << ", 1))\n";
  return true;
}
ParticleIndexPairs NearestNeighborsClosePairsFinder::get_close_pairs(
    kernel::Model *m, const kernel::ParticleIndexes &pai) const {
  kernel::ParticlesTemp c = IMP::get_particles(m, pai);
  IMP_NEW(algebra::NearestNeighborD<3>, nn, (c.begin(), c.end(), 0));
  double rm = max_radius(c.begin(), c.end());
  kernel::ParticleIndexPairs ret;
  for (unsigned int i = 0; i < c.size(); ++i) {
    XYZR d(c[i]);
    Ints cur = nn->get_in_ball(d.get_coordinates(),
                               rm + get_distance() + d.get_radius());
    for (unsigned int j = 0; j < cur.size(); ++j) {
      if (d < c[cur[j]]) {
        ret.push_back(
            kernel::ParticleIndexPair(pai[cur[j]], d.get_particle_index()));
      }
    }
  }
  return ret;
}
Ejemplo n.º 23
0
int KMCentersNode::mid_center(const Ints &cands) {
    KMPoint *lo, *hi, mid;
    lo = bnd_box_.get_point(0);
    hi = bnd_box_.get_point(1);
    // get the mid point of the bounding box
    for (int d = 0; d < bnd_box_.get_dim(); d++) {
        mid.push_back(((*lo)[d] + (*hi)[d]) / 2);
    }
    // the closest center will be the closest to the middle of the bounding box
    double min_dist = km_distance2(mid, *((*centers_)[cands[0]]));
    int min_ind = 0;
    for (unsigned int j = 1; j < cands.size(); j++) {
        double dist = km_distance2(mid, *((*centers_)[cands[j]]));
        if (dist < min_dist) {
            min_dist = dist;
            min_ind = j;
        }
    }
    return cands[min_ind];
}
Ejemplo n.º 24
0
Ints _pass_ints(Ints in) {
  for (unsigned int i = 0; i < in.size(); ++i) {
    std::cout << in[i] << " ";
  }
  return in;
}
Ejemplo n.º 25
0
double
get_slack_estimate(const ParticlesTemp& ps,
                   double upper_bound,
                   double step,
                   const RestraintsTemp &restraints,
                   bool derivatives,
                   Optimizer *opt,
                   ClosePairContainer *cpc) {
  std::vector<Data> datas;
  for (double slack=0; slack< upper_bound; slack+= step) {
    IMP_LOG(VERBOSE, "Computing for " << slack << std::endl);
    datas.push_back(Data());
    datas.back().slack=slack;
    {
      boost::timer imp_timer;
      int count=0;
      base::SetLogState sl(opt->get_model(), SILENT);
      do {
        cpc->set_slack(slack);
        cpc->update();
        ++count;
      } while (imp_timer.elapsed()==0);
      datas.back().ccost= imp_timer.elapsed()/count;
      IMP_LOG(VERBOSE, "Close pair finding cost "
              << datas.back().ccost << std::endl);
    }
    {
      boost::timer imp_timer;
      double score=0;
      int count=0;
      int iters=1;
      base::SetLogState sl(opt->get_model(), SILENT);
      do {
        for ( int j=0; j< iters; ++j) {
          for (unsigned int i=0; i< restraints.size(); ++i) {
            score+=restraints[i]->evaluate(derivatives);
            // should restore
          }
        }
        count += iters;
        iters*=2;
      } while (imp_timer.elapsed()==0);
      datas.back().rcost= imp_timer.elapsed()/count;
      IMP_LOG(VERBOSE, "Restraint evaluation cost "
              << datas.back().rcost << std::endl);
    }
  }
  int ns=100;
  int last_ns=1;
  int opt_i=-1;
  std::vector<Floats > dists(1, Floats(1,0.0));
  std::vector< std::vector<algebra::Vector3D> >
    pos(1, std::vector<algebra::Vector3D>(ps.size()));
  for (unsigned int j=0; j< ps.size(); ++j) {
    pos[0][j]=core::XYZ(ps[j]).get_coordinates();
  }
  do {
    IMP_LOG(VERBOSE, "Stepping from " << last_ns << " to " << ns << std::endl);
    dists.resize(ns, Floats(ns, 0.0));
    for ( int i=0; i< last_ns; ++i) {
      dists[i].resize(ns, 0.0);
    }
    pos.resize(ns,  std::vector<algebra::Vector3D>(ps.size()));
    base::SetLogState sl(opt->get_model(), SILENT);
    for ( int i=last_ns; i< ns; ++i) {
      opt->optimize(1);
      for (unsigned int j=0; j< ps.size(); ++j) {
        pos[i][j]=core::XYZ(ps[j]).get_coordinates();
      }
    }
    for ( int i=last_ns; i< ns; ++i) {
      for ( int j=0; j< i; ++j) {
        double md=0;
        for (unsigned int k=0; k< ps.size(); ++k) {
          md= std::max(md, algebra::get_distance(pos[i][k], pos[j][k]));
        }
        dists[i][j]=md;
        dists[j][i]=md;
      }
    }
    // estimate lifetimes from slack
    for (unsigned int i=0; i< datas.size(); ++i) {
      Ints deaths;
      for ( int j=0; j< ns; ++j) {
        for ( int k=j+1; k < ns; ++k) {
          if (dists[j][k]> datas[i].slack) {
            deaths.push_back(k-j);
            break;
          }
        }
      }
      std::sort(deaths.begin(), deaths.end());
      // kaplan meier estimator
      double ml=0;
      if (deaths.empty()) {
        ml= ns;
      } else {
        //double l=1;
        IMP_INTERNAL_CHECK(deaths.size() < static_cast<unsigned int>(ns),
                           "Too much death");
        double S=1;
        for (unsigned int j=0; j< deaths.size(); ++j) {
          double n= ns-j;
          double t=(n-1.0)/n;
          ml+=(S-t*S)*deaths[j];
          S*=t;
        }
      }
      datas[i].lifetime=ml;
      IMP_LOG(VERBOSE, "Expected life of " << datas[i].slack
              << " is " << datas[i].lifetime << std::endl);
    }

    /**
       C(s) is cost to compute
       R(s) is const to eval restraints
       L(s) is lifetime of slack
       minimize C(s)/L(s)+R(s)
    */
    // smooth
    for (unsigned int i=1; i< datas.size()-1; ++i) {
      datas[i].rcost=(datas[i].rcost+ datas[i-1].rcost+datas[i+1].rcost)/3.0;
      datas[i].ccost=(datas[i].ccost+ datas[i-1].ccost+datas[i+1].ccost)/3.0;
      datas[i].lifetime=(datas[i].lifetime
                      + datas[i-1].lifetime+datas[i+1].lifetime)/3.0;
    }
    double min= std::numeric_limits<double>::max();
    for (unsigned int i=0; i< datas.size(); ++i) {
      double v= datas[i].rcost+ datas[i].ccost/datas[i].lifetime;
      IMP_LOG(VERBOSE, "Cost of " << datas[i].slack << " is " << v
              << " from " << datas[i].rcost
              << " " << datas[i].ccost << " " << datas[i].lifetime
              << std::endl);
      if (v < min) {
        min=v;
        opt_i=i;
      }
    }
    last_ns=ns;
    ns*=2;
    IMP_LOG(VERBOSE, "Opt is " << datas[opt_i].slack << std::endl);
    // 2 for the value, 2 for the doubling
    // if it more than 1000, just decide that is enough
  } while (datas[opt_i].lifetime > ns/4.0 && ns <1000);
  return datas[opt_i].slack;
}
Ejemplo n.º 26
0
Archivo: pdb.cpp Proyecto: salilab/imp
void write_pdb(const ParticlesTemp& ps, TextOutput out) {
  IMP_FUNCTION_LOG;
  int last_index = 0;
  bool use_input_index = true;
  for (unsigned int i = 0; i < ps.size(); ++i) {
    if (Atom(ps[i]).get_input_index() != last_index + 1) {
      use_input_index = false;
      break;
    } else {
      ++last_index;
    }
  }
  for (unsigned int i = 0; i < ps.size(); ++i) {
    if (Atom::get_is_setup(ps[i])) {
      Atom ad(ps[i]);
      Residue rd = get_residue(ad);
      // really dumb and slow, fix later
      char chain;
      Chain c = get_chain(rd);
      if (c) {
        chain = c.get_id()[0];
      } else {
        chain = ' ';
      }
      int inum = i+1;
      if (i>=99999) inum=99999;
      out.get_stream() << get_pdb_string(
                              core::XYZ(ps[i]).get_coordinates(),
                              use_input_index ? ad.get_input_index()
                                              : static_cast<int>(inum),
                              ad.get_atom_type(), rd.get_residue_type(), chain,
                              rd.get_index(), rd.get_insertion_code(),
                              ad.get_occupancy(), ad.get_temperature_factor(),
                              ad.get_element());

      if (!out) {
        IMP_THROW("Error writing to file in write_pdb", IOException);
      }
    }
    else if (Residue::get_is_setup(ps[i])) {    // if C-alpha residue is available
      Residue rd = IMP::atom::Residue(ps[i]);
      // comment 1 by SJ - TODO: How to retrieve the correct chain information without an hierarchy?
      char chain;
      Chain c = get_chain(rd);
      if (c) {
        chain = c.get_id()[0];
      } else {
        chain = ' ';
      }

      // comment 2 by SJ - TODO: The C-alpha residues are not sorted yet. We need to sort the residues similarly to what PMI does.
      out.get_stream() << get_pdb_string(
                              core::XYZ(ps[i]).get_coordinates(),
                              static_cast<int>(i + 1),
                              IMP::atom::AT_CA, rd.get_residue_type(), chain,
                              rd.get_index(), ' ',
                              1.0, IMP::core::XYZR(ps[i]).get_radius());
    }
    else {  // if a coarse-grained BEAD is available
      Ints resindexes = IMP::atom::Fragment(ps[i]).get_residue_indexes();
      int resindex = (int)resindexes.front() + (int)(resindexes.size()/2);
      // comment 1 by SJ - TODO: How to retrieve the correct chain information without an hierarchy?
      char chain = ' ';

      // comment 3 by SJ - TODO: The BEADs are not sorted yet. We need to sort the residues similarly to what PMI does.
      // comment 4 by SJ - TODO: currently IMP does not allow "BEA" as a residue name, while PMI allows it. Thus "UNK" was used instead.
      out.get_stream() << get_pdb_string(
                              core::XYZ(ps[i]).get_coordinates(),
                              static_cast<int>(i + 1),
                              IMP::atom::AT_CA, IMP::atom::UNK, chain,
                              (int)resindex, ' ',
                              1.0, IMP::core::XYZR(ps[i]).get_radius());
    }
  }
}