File: optimizeMesh.cpp

package info (click to toggle)
camitk 6.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 389,508 kB
  • sloc: cpp: 103,476; sh: 2,448; python: 1,618; xml: 984; makefile: 128; perl: 84; sed: 20
file content (399 lines) | stat: -rw-r--r-- 13,182 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#include <math.h>
#include <iostream>
#include <string>
using namespace std;

#include <pml/PhysicalModel.h>
#include <pml/MultiComponent.h>
#include <pml/StructuralComponent.h>
#include <pml/Atom.h>

/// global variables
// -------------------- the physical model being processed ------------------------
PhysicalModel* pm;

// -------------------- all cluster ------------------------
class Cluster;
vector <Cluster*> allClusters;

// first atom is now replaced by 2nd atom
map<Atom*, Atom*> replacement;

double precision;
unsigned int nrOfNewAtoms;

/** class Cluster
 *
 *  a cluster is a set of point that are nearly at the same place (at a given precision)
 */
class Cluster {
public:
    /// create a cluster of this atom, using the given precision
    Cluster(double distance);

    ~Cluster();

    /// get composing atom by index
    Atom* getAtom(unsigned int id);

    /// add an atom to the cluster if in the given precision (true if added) (update center)
    bool addAtom(Atom*);

    /// get the center (create if necessary)
    Atom* getCenter();

    /// get nr of atoms in the cluster
    unsigned int nrOfAtoms();

    /// current atom index for new atoms
    static unsigned int atomIndex;

private:
    /// cluster center
    Atom* center;

    /// the cluster cell
    Cell* myCell;

    /// distance precision
    double distance;

    /// update center position
    void updateCenter();
};

unsigned int Cluster::atomIndex = 10000;


// -------------------- constructor/destructor ------------------------
Cluster::Cluster(double distance) {
    this->distance = distance;
    myCell = new Cell(pm, StructureProperties::POLY_VERTEX);
    center = new Atom(pm, Cluster::atomIndex++);
    Cluster::atomIndex++;
    nrOfNewAtoms++;
    //pm->addAtom(center);
}

Cluster::~Cluster() {
    delete myCell;
    delete center;
}

// -------------------- updateCenter ------------------------
void Cluster::updateCenter() {
    double pos[3];
    double posC[3];
    unsigned int size = myCell->getNumberOfStructures();

    for (unsigned int j = 0; j < 3; j++) {
        posC[j] = 0.0;
    }

    for (unsigned int i = 0; i < size; i++) {
        ((Atom*)myCell->getStructure(i))->getPosition(pos);
        for (unsigned int j = 0; j < 3; j++) {
            posC[j] += pos[j];
        }
    }

    for (unsigned int j = 0; j < 3; j++) {
        posC[j] /= ((double)size);
    }

    center->setPosition(posC);
}

// -------------------- getCenter ------------------------
Atom* Cluster::getCenter() {
    return center;
}

// -------------------- getAtom ------------------------
Atom* Cluster::getAtom(unsigned int id) {
    return ((Atom*)myCell->getStructure(id));
}

// -------------------- nrOfAtoms ------------------------
unsigned int Cluster::nrOfAtoms() {
    return myCell->getNumberOfStructures();
}

// -------------------- addAtom ------------------------
bool Cluster::addAtom(Atom* a) {
    double posC[3];
    center->getPosition(posC);
    double pos[3];
    a->getPosition(pos);
    double dist = 0.0;
    for (unsigned int i = 0; i < 3; i++) {
        dist += (posC[i] - pos[i]) * (posC[i] - pos[i]);
    }
    dist = sqrt(dist);

    if (nrOfAtoms() == 0 || dist < distance) {
        myCell->addStructure(a);
        updateCenter();
        return true;
    }
    else {
        return false;
    }
}


// -------------------- insert ------------------------
Cluster* insert(Atom* a) {
    vector <Cluster*>::iterator it;

    // look into allClusters for equivalence
    it = allClusters.begin();
    while (it != allClusters.end() && !(*it)->addAtom(a)) {
        ++it;
    }

    // not found => insert
    if (it == allClusters.end()) {
        // no cluster found: create a new one
        Cluster* c = new Cluster(precision);
        c->addAtom(a);
        allClusters.push_back(c);
        return c;
    }
    else  {
        return (*it);
    }

}

// -------------------- update ------------------------
void update(MultiComponent* mc) {
    if (mc == nullptr) {
        cout << "0 cells)" << endl;
        return;
    }

    cout << mc->getNumberOfCells() << " cells)" << endl;
    unsigned int degeneratedCount = 0;

    // WARNING non-rentrant loop
    for (unsigned int i = 0; i < mc->getNumberOfCells(); i++) {
        Cell* c = mc->getCell(i);
        StructuralComponent* sc = c->getAtoms();
        c->deleteAllStructures();
        cout << '\r' << i << flush;
        // remove previous list
        for (unsigned int j = 0; j < sc->getNumberOfStructures(); j++) {
            c->removeStructure(sc->getStructure(j));
        }
        // check it was done properly
        if (c->getNumberOfStructures() > 0)  {
            cout << "Cell #" << c->getIndex() << " cannot delete all atoms (still has " << c->getNumberOfStructures() << ")" << endl;
        }
        // add new atoms
        map<Atom*, Atom*>::iterator proxy;
        for (unsigned int j = 0; j < sc->getNumberOfStructures(); j++) {
            proxy = replacement.find((Atom*)sc->getStructure(j));
            if (proxy == replacement.end()) {
                // not found?!
                cout << "Cell #" << c->getIndex() << " cannot find replacement for Atom#" << sc->getStructure(i)->getIndex() << endl;
            }
            else {
                c->addStructureIfNotIn(proxy->second);
            }
        }
        // check that the cell did not degenerate
        StructureProperties::GeometricType t = c->getType();
        int normalSize = ((t == StructureProperties::LINE) ? 2 :
                          ((t == StructureProperties::TRIANGLE) ? 3 :
                           ((t == StructureProperties::QUAD) ? 4 :
                            ((t == StructureProperties::TETRAHEDRON) ? 4 :
                             ((t == StructureProperties::WEDGE) ? 6 :
                              ((t == StructureProperties::HEXAHEDRON) ? 8 : -1))))));
        if (normalSize != -1 && normalSize != (int)c->getNumberOfStructures()) {
            cout << "deleting degenerated Cell #" << c->getIndex() << ": it is a " <<
                 StructureProperties::toString(t) << " and should have " << normalSize <<
                 " atoms, but has now " << c->getNumberOfStructures() << flush;
            degeneratedCount++;
            c->getStructuralComponent(0)->removeStructure(c);
            // a cell was deleted, as it is a non re-entrant loop, get back one index
            i--;
        }
    }
    cout << flush;
    cout << degeneratedCount << " degenerated cells removed                                                        " << endl;
}

// -------------------- saveClusters ------------------------
void saveClusters(string clusterFile) {
    stringstream clusterOSS;
    clusterOSS << precision;


    string nonClusterFile = clusterFile;
    unsigned int pLast = clusterFile.rfind(".");

    if (pLast != string::npos) {
        clusterFile.erase(pLast);
        clusterFile += "-clusters-" + clusterOSS.str() + ".txt";
    }
    else {
        clusterFile = "clusters-" + clusterOSS.str() + ".txt";
    }

    pLast = nonClusterFile.rfind(".");
    if (pLast != string::npos) {
        nonClusterFile.erase(pLast);
        nonClusterFile += "-non-clusters-" + clusterOSS.str() + ".txt";
    }
    else {
        nonClusterFile = "non-clusters-" + clusterOSS.str() + ".txt";
    }

    cout << "-> please wait while saving cluster informations in " << clusterFile << " (" << pm->getNumberOfAtoms() - allClusters.size() << " clusters) and non-clusters in " << nonClusterFile << endl;
    ofstream clusterOutputFile(clusterFile.c_str());
    ofstream nonClusterOutputFile(nonClusterFile.c_str());
    for (vector <Cluster*>::iterator it = allClusters.begin(); it != allClusters.end(); ++it) {
        if ((*it)->nrOfAtoms() > 1) {
            clusterOutputFile << (*it)->getCenter()->getIndex() << " : ";
            for (unsigned int i = 0; i < (*it)->nrOfAtoms(); i++) {
                clusterOutputFile << (*it)->getAtom(i)->getIndex() << " ";
            }
            clusterOutputFile << endl;
        }
        else {
            nonClusterOutputFile << (*it)->getAtom(0)->getIndex() << endl;
        }
    }
    clusterOutputFile.close();
    nonClusterOutputFile.close();
}

// -------------------- optimize ------------------------
void optimize(string clusterFile) {
    StructuralComponent* atoms = pm->getAtoms();

    // create clusters
    for (unsigned int i = 0; i < atoms->getNumberOfStructures(); i++) {
        insert((Atom*) atoms->getStructure(i));
        cout << '\r' <<  i << flush;
    }
    cout << endl;

    cout << "found " << allClusters.size() << " clusters, for " <<  atoms->getNumberOfStructures() << " atoms" << endl;
    cout << "-> please wait while removing " << atoms->getNumberOfStructures() - allClusters.size() << " atoms" << endl;

    // create newAtoms with all atoms that are alone in their clusters and
    // all cluster centers
    StructuralComponent* newAtoms = new StructuralComponent(pm);
    for (vector <Cluster*>::iterator it = allClusters.begin(); it != allClusters.end(); ++it) {
        if ((*it)->nrOfAtoms() == 1) {
            newAtoms->addStructure((*it)->getAtom(0));
            replacement.insert(pair<Atom*, Atom*>((*it)->getAtom(0), (*it)->getAtom(0)));
        }
        else {
            newAtoms->addStructure((*it)->getCenter());
            // memorize replacements
            for (unsigned int i = 0; i < (*it)->nrOfAtoms(); i++) {
                replacement.insert(pair<Atom*, Atom*>((*it)->getAtom(i), (*it)->getCenter()));
            }
        }
    }

    // save the clusters and non cluster
    saveClusters(clusterFile);

    // update all atoms using replacements
    cout << "-> please wait while replacing atoms in exclusive components (";
    update(pm->getExclusiveComponents());
    cout << "-> please wait while replacing atoms in informative components (";
    update(pm->getInformativeComponents());

    // Use new atoms instead of atoms
    cout << "-> please wait while changing atoms" << endl;
    pm->setAtoms(newAtoms, false); // do not delete old atom list!
}

// -------------------- main ------------------------
int main(int argc, char** argv) {

    if (argc != 3) {
        cout << "Usage:" << endl;
        cout << "\t" << argv[0] << " file.pml precision" << endl;
        cout << "output to: file-optimized-precision.pml" << endl;
        cout << "PML " << PhysicalModel::VERSION << endl;
        exit(-1);
    }

    try {
        precision = atof(argv[2]);
        // read the pml
        string filename(argv[1]);
        cout << "-> please wait while opening " << filename << " for optimizing precision " << precision << endl;
        pm = new PhysicalModel(filename.c_str());

        cout << "-> please wait while optimizing " << pm->getNumberOfAtoms() << " atoms..." << endl;

        optimize(filename);
        /*
        // now, we have the right component, let's do some work...
        nrOfNewAtoms = 0;
        StructuralComponent * refined = refine(sc);

        // add the new SC to the exclusive component
        if (refined)
            pm->getExclusiveComponents()->addSubComponent(refined);
        */

        // save the result
        stringstream clusterOSS;
        clusterOSS << precision;
        unsigned int pLast = filename.rfind(".");
        if (pLast != string::npos) {
            filename.erase(pLast);
            filename += "-optimized-" + clusterOSS.str() + ".pml";
        }
        else {
            filename = "optimized-" + clusterOSS.str() + ".pml";
        }

        cout << "-> please wait while saving " << filename << " (" << nrOfNewAtoms << " new atoms)" << endl;

        ofstream outputFile(filename.c_str());
        pm->setName(pm->getName() + " optimized for " + clusterOSS.str());
        // do not optimize output (do not touch cell and atom id)
        pm->xmlPrint(outputFile, false);
        outputFile.close();

        delete pm;
    }
    catch (const PMLAbortException& ae) {
        cout << "AbortException: Physical model aborted:" << endl ;
        cout << ae.what() << endl;
    }
}