<commit_before>#include "ofApp.h"
#include "asio.hpp"     //For socket integration
#include "oscpkt.hh"    //For OSC Serialzation
#include "ofxAubio.h"           //for aubio

//---------------------Global Var: ASIO------------------------------------

std::string s;
using asio::ip::udp;
asio::io_service io_service;
#define PORT "1331"

//---------------------Global Var: OSC-------------------------------------

using namespace oscpkt;
PacketWriter pkt;
Message msg;
const void * message;
int size;

//---------------------UDP Classes-----------------------------------------

class UDPClient
{
public:
    UDPClient(
              asio::io_service& io_service,
              const std::string& host,
              const std::string& port
              ) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0)) {
        udp::resolver resolver(io_service_);
        udp::resolver::query query(udp::v4(), host, port);
        udp::resolver::iterator iter = resolver.resolve(query);
        endpoint_ = *iter;
    }

    ~UDPClient()
    {
        socket_.close();
    }

    void send(const std::string& msg) {
        socket_.send_to(asio::buffer(msg, msg.size()), endpoint_);
    }

    void send_osc(const void *msg, int size) {
        socket_.send_to(asio::buffer(msg, size), endpoint_);
    }

private:
    asio::io_service& io_service_;
    udp::socket socket_;
    udp::endpoint endpoint_;
};

UDPClient client(io_service, "localhost", PORT);

//--------------------------------------------------------------
void ofApp::setup(){

    ofBackground(34, 34, 34);
    ofSetFrameRate(60);

    int sampleRate = 44100;
    //int bufferSize = 512;
    int outChannels = 0;
    int inChannels = 2;

    //--------------essentia setup

    // setup the sound stream
    soundStream.setup(this, outChannels, inChannels, sampleRate, bufferSize, 3);

    //setup ofxAudioAnalyzer with the SAME PARAMETERS
    audioAnalyzer.setup(sampleRate, bufferSize, inChannels);

    //--------------filterbank setup

    ofSetVerticalSync(true);
    ofBackground(54, 54, 54);
    ofSetFrameRate(60);

    int ticksPerBuffer = 8;

    int midiMin = 21;
    int midiMax = 108;

    filterBank.setup(bufferSize, midiMin, midiMax, inChannels, BANDWIDTH, sampleRate, 1.0);
    filterBank.setColor(ofColor::orange);

    //--------------aubio setup

    // setup onset object
    onset.setup();
    //onset.setup("mkl", 2 * bufferSize, bufferSize, sampleRate);
    // listen to onset event
    ofAddListener(onset.gotOnset, this, &ofApp::onsetEvent);

    // setup pitch object
    pitch.setup();
    //pitch.setup("yinfft", 8 * bufferSize, bufferSize, sampleRate);

    // setup beat object
    beat.setup();
    //beat.setup("default", 2 * bufferSize, bufferSize, samplerate);
    // listen to beat event
    ofAddListener(beat.gotBeat, this, &ofApp::beatEvent);

    // setup mel bands object
    bands.setup();

}

//--------------------------------------------------------------
void ofApp::update(){

    smooth = ofClamp(ofGetMouseX() / (float)ofGetWidth(), 0.0, 1.0);

    //get the analysis values
    rms_l = audioAnalyzer.getValue(RMS, 0, smooth);
    rms_r = audioAnalyzer.getValue(RMS, 1, smooth);

    //-:get Values:
    rms     = audioAnalyzer.getValue(RMS, 0, smoothing);
    power   = audioAnalyzer.getValue(POWER, 0, smoothing);
    pitchFreq = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing);
    pitchConf = audioAnalyzer.getValue(PITCH_CONFIDENCE, 0, smoothing);
    pitchSalience  = audioAnalyzer.getValue(PITCH_SALIENCE, 0, smoothing);
    inharmonicity   = audioAnalyzer.getValue(INHARMONICITY, 0, smoothing);
    hfc = audioAnalyzer.getValue(HFC, 0, smoothing);
    specComp = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing);
    centroid = audioAnalyzer.getValue(CENTROID, 0, smoothing);
    rollOff = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing);
    oddToEven = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing);
    strongPeak = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing);
    strongDecay = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing);
    //Normalized values for graphic meters:
    pitchFreqNorm   = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing, TRUE);
    hfcNorm     = audioAnalyzer.getValue(HFC, 0, smoothing, TRUE);
    specCompNorm = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing, TRUE);
    centroidNorm = audioAnalyzer.getValue(CENTROID, 0, smoothing, TRUE);
    rollOffNorm  = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing, TRUE);
    oddToEvenNorm   = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing, TRUE);
    strongPeakNorm  = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing, TRUE);
    strongDecayNorm = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing, TRUE);

    dissonance = audioAnalyzer.getValue(DISSONANCE, 0, smoothing);

    //Vector Parameters
    spectrum = audioAnalyzer.getValues(SPECTRUM, 0, smoothing);
    melBands = audioAnalyzer.getValues(MEL_BANDS, 0, smoothing);
    mfcc = audioAnalyzer.getValues(MFCC, 0, smoothing);
    hpcp = audioAnalyzer.getValues(HPCP, 0, smoothing);
    tristimulus = audioAnalyzer.getValues(TRISTIMULUS, 0, smoothing);

    //Boolean Parameter
    isOnset = audioAnalyzer.getOnsetValue(0);

    //For Testing
    std::cout<<"centroidNorm:"<<centroidNorm<<endl ;
    std::cout<<"strongDecayNorm:"<<strongDecayNorm<<endl ;

    // Make  & Send OSC Object
    pkt.startBundle();
    pkt.addMessage(msg.init("/essentia/rms").pushFloat(rms));
    pkt.addMessage(msg.init("/essentia/power").pushFloat(power));
    pkt.addMessage(msg.init("/essentia/pitchFreq").pushFloat(pitchFreq));
    pkt.addMessage(msg.init("/essentia/pitchConf").pushFloat(pitchConf));
    pkt.addMessage(msg.init("/essentia/pitchSalience").pushFloat(pitchSalience));
    pkt.addMessage(msg.init("/essentia/inharmonicity").pushFloat(inharmonicity));
    pkt.addMessage(msg.init("/essentia/hfc").pushFloat(hfc));
    pkt.addMessage(msg.init("/essentia/specComp").pushFloat(specComp));
    pkt.addMessage(msg.init("/essentia/centroid").pushFloat(centroid));
    pkt.addMessage(msg.init("/essentia/rollOff").pushFloat(rollOff));
    pkt.addMessage(msg.init("/essentia/oddToEven").pushFloat(oddToEven));
    pkt.addMessage(msg.init("/essentia/strongPeak").pushFloat(strongPeak));
    pkt.addMessage(msg.init("/essentia/strongDecay").pushFloat(strongDecay));
    //Normalized values for graphic meters:
    pkt.addMessage(msg.init("/essentia/pitchFreqNorm").pushFloat(pitchFreqNorm));
    pkt.addMessage(msg.init("/essentia/hfcNorm").pushFloat(hfcNorm));
    pkt.addMessage(msg.init("/essentia/specCompNorm").pushFloat(specCompNorm));
    pkt.addMessage(msg.init("/essentia/centroidNorm").pushFloat(centroidNorm));
    pkt.addMessage(msg.init("/essentia/rollOffNorm").pushFloat(rollOffNorm));
    pkt.addMessage(msg.init("/essentia/oddToEvenNorm").pushFloat(oddToEvenNorm));
    pkt.addMessage(msg.init("/essentia/strongPeakNorm").pushFloat(strongPeakNorm));
    pkt.addMessage(msg.init("/essentia/strongDecayNorm").pushFloat(strongDecayNorm));

    // Boolean, mapped to onset.
    pkt.addMessage(msg.init("/essentia/isOnset").pushFloat(isOnset));

    // Vector Parameters

    int spectrum_size=spectrum.size(); //257
    pkt.addMessage(msg.init("/essentia/spectrum"));
    for(int n=0; n<spectrum_size; n++)
    {   msg.pushFloat(spectrum[n]);
    }

    int melBands_size=melBands.size(); //24
    pkt.addMessage(msg.init("/essentia/melBands"));
    for(int n=0; n<melBands_size; n++)
    {   msg.pushFloat(melBands[n]);
    }

    int mfcc_size=mfcc.size();  //13
    pkt.addMessage(msg.init("/essentia/mfcc"));
    for(int n=0; n<mfcc_size; n++)
    {   msg.pushFloat(mfcc[n]);
    }

    int hpcp_size=hpcp.size();  //12
    pkt.addMessage(msg.init("/essentia/hpcp"));
    for(int n=0; n<hpcp_size; n++)
    {   msg.pushFloat(hpcp[n]);
    }

    int tristimulus_size=tristimulus.size(); //3
    pkt.addMessage(msg.init("/essentia/tristimulus"));
    for(int n=0; n<tristimulus_size; n++)
    {   msg.pushFloat(tristimulus[n]);
    }

    // Polyphonic Pitch from Filterbank
    float * polyphonic_pitch_pointer;
    float log_smth_energy;
    polyphonic_pitch_pointer=filterBank.getSmthEnergies();

    log_smth_energy = LIN2dB (polyphonic_pitch_pointer[filterBank.midiMinVar]);
    pkt.addMessage(msg.init("/essentia/PolyphonicPitch").pushFloat(log_smth_energy));
    std::cout<<"Midi Min= "<<filterBank.midiMinVar<<endl;
    std::cout<<"Midi Min= "<<filterBank.midiMaxVar<<endl;
    for(int n=filterBank.midiMinVar+1; n<filterBank.midiMaxVar; n++)  // 88
    {   log_smth_energy = LIN2dB (polyphonic_pitch_pointer[n]);
        std::cout<<log_smth_energy<<" ";
        msg.pushFloat(log_smth_energy);
    }
    std::cout<<endl;

    pkt.endBundle();
    if (pkt.isOk()) {
        message=pkt.packetData();
        size= pkt.packetSize();
        client.send_osc(message, size);
    }
    msg.clear();
    pkt.Reset();
}

//--------------------------------------------------------------
void ofApp::draw(){

   /* ofSetColor(ofColor::cyan);

    float xpos = ofGetWidth() *.5;
    float ypos = ofGetHeight() - ofGetHeight() * rms_r;
    float radius = 5 + 100*rms_l;

    ofDrawCircle(xpos, ypos, radius);

    //----------------

    ofSetColor(225);
    ofDrawBitmapString("ofxAudioAnalyzer - RMS SMOOTHING INPUT EXAMPLE", 32, 32);

    string infoString = "RMS Left: " + ofToString(rms_l) +
                        "\nRMS Right: " + ofToString(rms_r) +
                        "\nSmoothing (mouse x): " + ofToString(smooth);

    ofDrawBitmapString(infoString, 32, 579);*/

    ofSetColor(225);
    ofNoFill();

    float chSz = bufferSize/3;
    // draw the left input channel:
    {
        ofPushStyle();
        ofPushMatrix();
        ofTranslate(100, 15, 0);
        ofSetColor(225);
        ofDrawBitmapString("Left Channel", 4, 18);
        ofSetLineWidth(1);
        ofRect(0, 0, chSz, 200);
        ofSetColor(ofColor::orange);
        ofSetLineWidth(3);
        ofBeginShape();
        for (int i = 0; i < bufferSize; i++){
            ofVertex(i/(bufferSize/chSz), 100 - filterBank.getLeftBuffer()[i]*45);
        }
        ofEndShape(false);
        ofPopMatrix();
        ofPopStyle();
    }
    // draw the right input channel:
    {
        ofPushStyle();
        ofPushMatrix();
        ofTranslate(200+chSz, 15, 0);
        ofSetColor(225);
        ofDrawBitmapString("Right Channel", 4, 18);
        ofSetLineWidth(1);
        ofRect(0, 0, chSz, 200);
        ofSetColor(ofColor::orange);
        ofSetLineWidth(3);
        ofBeginShape();
        for (int i = 0; i < bufferSize; i++){
            ofVertex(i/(bufferSize/chSz), 100 - filterBank.getRightBuffer()[i]*45);
        }
        ofEndShape(false);
        ofPopMatrix();
        ofPopStyle();
    }

    //Draw FilterBank
    {
        ofPushStyle();
        ofPushMatrix();
        ofTranslate (100,250,0);
        filterBank.draw(800,400);
        ofPopMatrix();
        ofPopStyle();
    }
    ofSetColor(225);

    string reportString =  "Sampling Rate: "+ ofToString(SR) +"\nBuffer size: "+ ofToString(bufferSize);
    ofDrawBitmapString(reportString, 10, 700);

}
//--------------------------------------------------------------
void ofApp::audioIn(ofSoundBuffer &inBuffer){
    //ANALYZE SOUNDBUFFER:
    audioAnalyzer.analyze(inBuffer);

    //Analyze Input Buffer with ofxFilterbank
    vector <float> temp;
    temp = inBuffer.getBuffer();
    float *p = &temp[0];
    filterBank.analyze(p);
}

//--------------------------------------------------------------
void ofApp::exit(){
    ofSoundStreamStop();
    audioAnalyzer.exit();
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}

//==========Aubio

//----
void ofApp::onsetEvent(float & time) {
    //ofLog() << "got onset at " << time << " s";
    gotOnset = true;
}

//----
void ofApp::beatEvent(float & time) {
    //ofLog() << "got beat at " << time << " s";
    gotBeat = true;
}

<commit_msg>Aubio is incorporated into Essentia<commit_after>#include "ofApp.h"
#include "asio.hpp"     //For socket integration
#include "oscpkt.hh"    //For OSC Serialzation
#include "ofxAubio.h"           //for aubio

//---------------------Global Var: ASIO------------------------------------

std::string s;
using asio::ip::udp;
asio::io_service io_service;
#define PORT "1331"

//---------------------Global Var: OSC-------------------------------------

using namespace oscpkt;
PacketWriter pkt;
Message msg;
const void * message;
int size;

//---------------------UDP Classes-----------------------------------------

class UDPClient
{
public:
    UDPClient(
              asio::io_service& io_service,
              const std::string& host,
              const std::string& port
              ) : io_service_(io_service), socket_(io_service, udp::endpoint(udp::v4(), 0)) {
        udp::resolver resolver(io_service_);
        udp::resolver::query query(udp::v4(), host, port);
        udp::resolver::iterator iter = resolver.resolve(query);
        endpoint_ = *iter;
    }

    ~UDPClient()
    {
        socket_.close();
    }

    void send(const std::string& msg) {
        socket_.send_to(asio::buffer(msg, msg.size()), endpoint_);
    }

    void send_osc(const void *msg, int size) {
        socket_.send_to(asio::buffer(msg, size), endpoint_);
    }

private:
    asio::io_service& io_service_;
    udp::socket socket_;
    udp::endpoint endpoint_;
};

UDPClient client(io_service, "localhost", PORT);

//--------------------------------------------------------------
void ofApp::setup(){

    ofBackground(34, 34, 34);
    ofSetFrameRate(60);

    int sampleRate = 44100;
    //int bufferSize = 512;
    int outChannels = 0;
    int inChannels = 2;

    //--------------essentia setup

    // setup the sound stream
    soundStream.setup(this, outChannels, inChannels, sampleRate, bufferSize, 3);

    //setup ofxAudioAnalyzer with the SAME PARAMETERS
    audioAnalyzer.setup(sampleRate, bufferSize, inChannels);

    //--------------filterbank setup

    ofSetVerticalSync(true);
    ofBackground(54, 54, 54);
    ofSetFrameRate(60);

    int ticksPerBuffer = 8;

    int midiMin = 21;
    int midiMax = 108;

    filterBank.setup(bufferSize, midiMin, midiMax, inChannels, BANDWIDTH, sampleRate, 1.0);
    filterBank.setColor(ofColor::orange);

    //--------------aubio setup

    // setup onset object
    onset.setup();
    //onset.setup("mkl", 2 * bufferSize, bufferSize, sampleRate);
    // listen to onset event
    ofAddListener(onset.gotOnset, this, &ofApp::onsetEvent);

    // setup pitch object
    pitch.setup();
    //pitch.setup("yinfft", 8 * bufferSize, bufferSize, sampleRate);

    // setup beat object
    beat.setup();
    //beat.setup("default", 2 * bufferSize, bufferSize, samplerate);
    // listen to beat event
    ofAddListener(beat.gotBeat, this, &ofApp::beatEvent);

    // setup mel bands object
    bands.setup();

}

//--------------------------------------------------------------
void ofApp::update(){

    smooth = ofClamp(ofGetMouseX() / (float)ofGetWidth(), 0.0, 1.0);

    //get the analysis values
    rms_l = audioAnalyzer.getValue(RMS, 0, smooth);
    rms_r = audioAnalyzer.getValue(RMS, 1, smooth);

    //-:get Values:
    rms     = audioAnalyzer.getValue(RMS, 0, smoothing);
    power   = audioAnalyzer.getValue(POWER, 0, smoothing);
    pitchFreq = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing);
    pitchConf = audioAnalyzer.getValue(PITCH_CONFIDENCE, 0, smoothing);
    pitchSalience  = audioAnalyzer.getValue(PITCH_SALIENCE, 0, smoothing);
    inharmonicity   = audioAnalyzer.getValue(INHARMONICITY, 0, smoothing);
    hfc = audioAnalyzer.getValue(HFC, 0, smoothing);
    specComp = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing);
    centroid = audioAnalyzer.getValue(CENTROID, 0, smoothing);
    rollOff = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing);
    oddToEven = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing);
    strongPeak = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing);
    strongDecay = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing);
    //Normalized values for graphic meters:
    pitchFreqNorm   = audioAnalyzer.getValue(PITCH_FREQ, 0, smoothing, TRUE);
    hfcNorm     = audioAnalyzer.getValue(HFC, 0, smoothing, TRUE);
    specCompNorm = audioAnalyzer.getValue(SPECTRAL_COMPLEXITY, 0, smoothing, TRUE);
    centroidNorm = audioAnalyzer.getValue(CENTROID, 0, smoothing, TRUE);
    rollOffNorm  = audioAnalyzer.getValue(ROLL_OFF, 0, smoothing, TRUE);
    oddToEvenNorm   = audioAnalyzer.getValue(ODD_TO_EVEN, 0, smoothing, TRUE);
    strongPeakNorm  = audioAnalyzer.getValue(STRONG_PEAK, 0, smoothing, TRUE);
    strongDecayNorm = audioAnalyzer.getValue(STRONG_DECAY, 0, smoothing, TRUE);

    dissonance = audioAnalyzer.getValue(DISSONANCE, 0, smoothing);

    //Vector Parameters
    spectrum = audioAnalyzer.getValues(SPECTRUM, 0, smoothing);
    melBands = audioAnalyzer.getValues(MEL_BANDS, 0, smoothing);
    mfcc = audioAnalyzer.getValues(MFCC, 0, smoothing);
    hpcp = audioAnalyzer.getValues(HPCP, 0, smoothing);
    tristimulus = audioAnalyzer.getValues(TRISTIMULUS, 0, smoothing);

    //Boolean Parameter
    isOnset = audioAnalyzer.getOnsetValue(0);

    //For Testing
    std::cout<<"centroidNorm:"<<centroidNorm<<endl ;
    std::cout<<"strongDecayNorm:"<<strongDecayNorm<<endl ;

    // Make  & Send OSC Object
    pkt.startBundle();
    pkt.addMessage(msg.init("/essentia/rms").pushFloat(rms));
    pkt.addMessage(msg.init("/essentia/power").pushFloat(power));
    pkt.addMessage(msg.init("/essentia/pitchFreq").pushFloat(pitchFreq));
    pkt.addMessage(msg.init("/essentia/pitchConf").pushFloat(pitchConf));
    pkt.addMessage(msg.init("/essentia/pitchSalience").pushFloat(pitchSalience));
    pkt.addMessage(msg.init("/essentia/inharmonicity").pushFloat(inharmonicity));
    pkt.addMessage(msg.init("/essentia/hfc").pushFloat(hfc));
    pkt.addMessage(msg.init("/essentia/specComp").pushFloat(specComp));
    pkt.addMessage(msg.init("/essentia/centroid").pushFloat(centroid));
    pkt.addMessage(msg.init("/essentia/rollOff").pushFloat(rollOff));
    pkt.addMessage(msg.init("/essentia/oddToEven").pushFloat(oddToEven));
    pkt.addMessage(msg.init("/essentia/strongPeak").pushFloat(strongPeak));
    pkt.addMessage(msg.init("/essentia/strongDecay").pushFloat(strongDecay));
    //Normalized values for graphic meters:
    pkt.addMessage(msg.init("/essentia/pitchFreqNorm").pushFloat(pitchFreqNorm));
    pkt.addMessage(msg.init("/essentia/hfcNorm").pushFloat(hfcNorm));
    pkt.addMessage(msg.init("/essentia/specCompNorm").pushFloat(specCompNorm));
    pkt.addMessage(msg.init("/essentia/centroidNorm").pushFloat(centroidNorm));
    pkt.addMessage(msg.init("/essentia/rollOffNorm").pushFloat(rollOffNorm));
    pkt.addMessage(msg.init("/essentia/oddToEvenNorm").pushFloat(oddToEvenNorm));
    pkt.addMessage(msg.init("/essentia/strongPeakNorm").pushFloat(strongPeakNorm));
    pkt.addMessage(msg.init("/essentia/strongDecayNorm").pushFloat(strongDecayNorm));

    // Boolean, mapped to onset.
    pkt.addMessage(msg.init("/essentia/isOnset").pushFloat(isOnset));

    // Vector Parameters

    int spectrum_size=spectrum.size(); //257
    pkt.addMessage(msg.init("/essentia/spectrum"));
    for(int n=0; n<spectrum_size; n++)
    {   msg.pushFloat(spectrum[n]);
    }

    int melBands_size=melBands.size(); //24
    pkt.addMessage(msg.init("/essentia/melBands"));
    for(int n=0; n<melBands_size; n++)
    {   msg.pushFloat(melBands[n]);
    }

    int mfcc_size=mfcc.size();  //13
    pkt.addMessage(msg.init("/essentia/mfcc"));
    for(int n=0; n<mfcc_size; n++)
    {   msg.pushFloat(mfcc[n]);
    }

    int hpcp_size=hpcp.size();  //12
    pkt.addMessage(msg.init("/essentia/hpcp"));
    for(int n=0; n<hpcp_size; n++)
    {   msg.pushFloat(hpcp[n]);
    }

    int tristimulus_size=tristimulus.size(); //3
    pkt.addMessage(msg.init("/essentia/tristimulus"));
    for(int n=0; n<tristimulus_size; n++)
    {   msg.pushFloat(tristimulus[n]);
    }

    // Polyphonic Pitch from Filterbank
    float * polyphonic_pitch_pointer;
    float log_smth_energy;
    polyphonic_pitch_pointer=filterBank.getSmthEnergies();

    log_smth_energy = LIN2dB (polyphonic_pitch_pointer[filterBank.midiMinVar]);
    pkt.addMessage(msg.init("/essentia/PolyphonicPitch").pushFloat(log_smth_energy));
    std::cout<<"Midi Min= "<<filterBank.midiMinVar<<endl;
    std::cout<<"Midi Min= "<<filterBank.midiMaxVar<<endl;
    for(int n=filterBank.midiMinVar+1; n<filterBank.midiMaxVar; n++)  // 88
    {   log_smth_energy = LIN2dB (polyphonic_pitch_pointer[n]);
        std::cout<<log_smth_energy<<" ";
        msg.pushFloat(log_smth_energy);
    }
    std::cout<<endl;

    // Onsets, BPM and monophonic pitch from Aubio

    onset.setThreshold(onsetThreshold);

    onsetNovelty = onset.novelty;
    onsetThresholdedNovelty = onset.thresholdedNovelty;
    std::cout<<"Onset Threshold Novelty:"<<onsetThresholdedNovelty<<endl ;

    // update pitch info
    pitchConfidence = pitch.pitchConfidence;
    if (pitch.latestPitch) midiPitch = pitch.latestPitch;
    std::cout<<"Pitch:"<<midiPitch<<endl ;

    // update BPM
    bpm = beat.bpm;
    std::cout<<"BPM:"<<bpm<<endl ;

    pkt.addMessage(msg.init("/aubio/onset").pushFloat(onset.thresholdedNovelty));
    pkt.addMessage(msg.init("/aubio/midiPitch").pushFloat(pitch.latestPitch));
    pkt.addMessage(msg.init("/aubio/bpm").pushFloat(beat.bpm));

    pkt.endBundle();
    if (pkt.isOk()) {
        message=pkt.packetData();
        size= pkt.packetSize();
        client.send_osc(message, size);
    }
    msg.clear();
    pkt.Reset();
}

//--------------------------------------------------------------
void ofApp::draw(){

   /* ofSetColor(ofColor::cyan);

    float xpos = ofGetWidth() *.5;
    float ypos = ofGetHeight() - ofGetHeight() * rms_r;
    float radius = 5 + 100*rms_l;

    ofDrawCircle(xpos, ypos, radius);

    //----------------

    ofSetColor(225);
    ofDrawBitmapString("ofxAudioAnalyzer - RMS SMOOTHING INPUT EXAMPLE", 32, 32);

    string infoString = "RMS Left: " + ofToString(rms_l) +
                        "\nRMS Right: " + ofToString(rms_r) +
                        "\nSmoothing (mouse x): " + ofToString(smooth);

    ofDrawBitmapString(infoString, 32, 579);*/

    ofSetColor(225);
    ofNoFill();

    float chSz = bufferSize/3;
    // draw the left input channel:
    {
        ofPushStyle();
        ofPushMatrix();
        ofTranslate(100, 15, 0);
        ofSetColor(225);
        ofDrawBitmapString("Left Channel", 4, 18);
        ofSetLineWidth(1);
        ofRect(0, 0, chSz, 200);
        ofSetColor(ofColor::orange);
        ofSetLineWidth(3);
        ofBeginShape();
        for (int i = 0; i < bufferSize; i++){
            ofVertex(i/(bufferSize/chSz), 100 - filterBank.getLeftBuffer()[i]*45);
        }
        ofEndShape(false);
        ofPopMatrix();
        ofPopStyle();
    }
    // draw the right input channel:
    {
        ofPushStyle();
        ofPushMatrix();
        ofTranslate(200+chSz, 15, 0);
        ofSetColor(225);
        ofDrawBitmapString("Right Channel", 4, 18);
        ofSetLineWidth(1);
        ofRect(0, 0, chSz, 200);
        ofSetColor(ofColor::orange);
        ofSetLineWidth(3);
        ofBeginShape();
        for (int i = 0; i < bufferSize; i++){
            ofVertex(i/(bufferSize/chSz), 100 - filterBank.getRightBuffer()[i]*45);
        }
        ofEndShape(false);
        ofPopMatrix();
        ofPopStyle();
    }

    //Draw FilterBank
    {
        ofPushStyle();
        ofPushMatrix();
        ofTranslate (100,250,0);
        filterBank.draw(800,400);
        ofPopMatrix();
        ofPopStyle();
    }
    ofSetColor(225);

    string reportString =  "Sampling Rate: "+ ofToString(SR) +"\nBuffer size: "+ ofToString(bufferSize);
    ofDrawBitmapString(reportString, 10, 700);

}
//--------------------------------------------------------------
void ofApp::audioIn(ofSoundBuffer &inBuffer){
    //ANALYZE SOUNDBUFFER:
    audioAnalyzer.analyze(inBuffer);

    //Analyze Input Buffer with ofxFilterbank
    vector <float> temp;
    temp = inBuffer.getBuffer();
    float *p = &temp[0];
    filterBank.analyze(p);

    int inChannels=2;

    //Aubio
    // compute onset detection
    onset.audioIn(p, bufferSize, inChannels);
    // compute pitch detection
    pitch.audioIn(p, bufferSize, inChannels);
    // compute beat location
    beat.audioIn(p, bufferSize, inChannels);
    // compute bands
    bands.audioIn(p, bufferSize, inChannels);
}

//--------------------------------------------------------------
void ofApp::exit(){
    ofSoundStreamStop();
    audioAnalyzer.exit();
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}

//==========Aubio

//----
void ofApp::onsetEvent(float & time) {
    //ofLog() << "got onset at " << time << " s";
    gotOnset = true;
}

//----
void ofApp::beatEvent(float & time) {
    //ofLog() << "got beat at " << time << " s";
    gotBeat = true;
}

<|endoftext|>


<commit_before>#include <algorithm>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "antsUtilities.h"
#include <algorithm>

#include "itkTransform.h"
#include "itkCompositeTransform.h"
#include "itkDisplacementFieldTransform.h"
#include "antsCommandLineParser.h"
#include "itkantsReadWriteTransform.h"
#include "itkTransformFactory.h"

namespace ants
{
static bool MatOffRegistered[2] = { false, false };

template <unsigned int VImageDimension>
void RegisterMatOff()
{
  if( !MatOffRegistered[VImageDimension - 2] )
    {
    MatOffRegistered[VImageDimension - 2] = true;
    // Register the matrix offset transform base class to the
    // transform factory for compatibility with the current ANTs.
    typedef itk::MatrixOffsetTransformBase<double, VImageDimension,
                                           VImageDimension> MatrixOffsetTransformType;
    itk::TransformFactory<MatrixOffsetTransformType>::RegisterTransform();
    }
}

/**
 * print the usage and exit
 */
void PrintGenericUsageStatement()
{
  antscout << "Usage: CompositeTransformUtil --disassemble <CompositeTransform FileName>"
           << " <transform name prefix>" << std::endl
           << "or" << std::endl
           << "CompositeTransformUtil  --assemble <CompositeTransform> "
           << "<transform 1> <transform 2 > ... <transform N>" << std::endl;
}

/**
 * given a composite transform, write out all its component
 * transforms.
 */
template <unsigned int VImageDimension>
int
Disassemble(itk::TransformBase *transform, const std::string & transformName, const std::string & prefix)
{
  typedef itk::CompositeTransform<double, VImageDimension>                  CompositeTransformType;
  typedef typename CompositeTransformType::TransformTypePointer             TransformPointer;
  typedef typename itk::DisplacementFieldTransform<double, VImageDimension> DisplacementFieldTransformType;
  typedef typename DisplacementFieldTransformType::DisplacementFieldType    DisplacementFieldType;

  CompositeTransformType *composite = dynamic_cast<CompositeTransformType *>(transform);
  if( composite == 0 )
    {
    antscout << "Transform File " << transformName << " is a "
             << transform->GetNameOfClass() << " not a Composite Transform."
             << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int numTransforms = composite->GetNumberOfTransforms();
  for( unsigned int i = 0; i < numTransforms; ++i )
    {
    TransformPointer                curXfrm = composite->GetNthTransform(i);
    DisplacementFieldTransformType *dispXfrm =
      dynamic_cast<DisplacementFieldTransformType *>(curXfrm.GetPointer() );
    std::stringstream fname;
    fname << std::setfill('0') << std::setw(2) << i
          << "_" << prefix << "_"
          << curXfrm->GetNameOfClass();
    if( dispXfrm != 0 )
      {
      fname << ".nii.gz";    // if it's a displacement field transform
      }
    else
      {
      fname << ".txt";
      }
    itk::ants::WriteTransform<VImageDimension>(curXfrm, fname.str() );
    }
  return EXIT_SUCCESS;
}

int Disassemble(const std::string & CompositeName,
                const std::string & Prefix)
{
  itk::TransformBase::Pointer transform = itk::ants::ReadTransform<2>(CompositeName).GetPointer();

  if( transform.IsNull() )
    {
    transform = itk::ants::ReadTransform<3>(CompositeName).GetPointer();
    if( transform.IsNull() )
      {
      return EXIT_FAILURE; // ReadTransform prints error messages on
                           // failure.
      }
    }
  const unsigned int inDim(transform->GetInputSpaceDimension() );
  const unsigned int outDim(transform->GetOutputSpaceDimension() );
  if( inDim != outDim )
    {
    antscout << "Can't handle mixed input & output dimension: input("
             << inDim << ") output (" << outDim << ")" << std::endl;
    return EXIT_FAILURE;
    }

  switch( inDim )
    {
    case 2:
      return Disassemble<2>(transform, CompositeName, Prefix);
    case 3:
      return Disassemble<3>(transform, CompositeName, Prefix);
    default:
      antscout << "Unknown dimension " << inDim << std::endl;
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

template <unsigned int VImageDimension>
int
Assemble(const std::string & CompositeName,
         const std::vector<std::string> & transformNames,
         typename itk::CompositeTransform<double, VImageDimension>::TransformType::Pointer & firstTransform)
{
  typedef itk::CompositeTransform<double, VImageDimension> CompositeTransformType;
  typedef typename CompositeTransformType::TransformType   TransformType;
  typename CompositeTransformType::Pointer composite = CompositeTransformType::New();
  composite->AddTransform(firstTransform);
  for( unsigned int i = 1; i < transformNames.size(); ++i )
    {
    typename TransformType::Pointer curXfrm = itk::ants::ReadTransform<VImageDimension>(transformNames[i]);
    if( curXfrm.IsNull() )
      {
      return EXIT_FAILURE; // ReadTransform will complain if anything goes wrong.
      }
    composite->AddTransform(curXfrm);
    }
  typename TransformType::Pointer genericXfrmPtr = composite.GetPointer();
  return itk::ants::WriteTransform<VImageDimension>(genericXfrmPtr, CompositeName);
}

int Assemble(const std::string & CompositeName,
             const std::vector<std::string> & transformNames)
{
  typedef itk::CompositeTransform<double, 2>::TransformType Transform2DType;
  typedef itk::CompositeTransform<double, 3>::TransformType Transform3DType;

  Transform2DType::Pointer transform2D = itk::ants::ReadTransform<2>(transformNames[0]);
  if( transform2D.IsNotNull() )
    {
    return Assemble<2>(CompositeName, transformNames, transform2D);
    }
  Transform3DType::Pointer transform3D = itk::ants::ReadTransform<3>(transformNames[0]);
  if( transform3D.IsNotNull() )
    {
    return Assemble<3>(CompositeName, transformNames, transform3D);
    }
  return EXIT_FAILURE;
}

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int CompositeTransformUtil( std::vector<std::string> args, std::ostream* out_stream = NULL )
{
  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle
  args.insert( args.begin(), "CompositeTransformUtil" );
  std::remove( args.begin(), args.end(), std::string( "" ) );
  std::remove( args.begin(), args.end(), std::string( "" ) );
  int     argc = args.size();
  char* * argv = new char *[args.size() + 1];
  for( unsigned int i = 0; i < args.size(); ++i )
    {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy( argv[i], args[i].c_str(), args[i].length() );
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
    }
  argv[argc] = 0;
  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
public:
    Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
    {
    }

    ~Cleanup_argv()
    {
      for( unsigned int i = 0; i < argc_plus_one; ++i )
        {
        delete[] argv[i];
        }
      delete[] argv;
    }

private:
    char* *      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv( argv, argc + 1 );

  antscout->set_stream( out_stream );
  if( argc >= 2 && ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
    {
    PrintGenericUsageStatement();
    return EXIT_SUCCESS;
    }

  if( argc < 2 )
    {
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }
  ++argv; --argc;
  std::string action(*argv);
  ++argv; --argc;
  if( argc == 0 )
    {
    antscout << "Missing CompositeTransformName" << std::endl;
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }

  RegisterMatOff<2>();
  RegisterMatOff<3>();

  std::string CompositeName(*argv);
  ++argv; --argc;
  if( action == "--disassemble" )
    {
    if( argc == 0 )
      {
      antscout << "Missing output transforms prefix" << std::endl;
      PrintGenericUsageStatement();
      return EXIT_FAILURE;
      }
    std::string Prefix(*argv);
    return Disassemble(CompositeName, Prefix);
    }
  else if( action != "--assemble" )
    {
    antscout << "Unknown action " << action << std::endl;
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }
  std::vector<std::string> transformNames;
  while( argc > 0 )
    {
    std::string transformName(*argv);
    ++argv; --argc;
    transformNames.push_back(transformName);
    }

  if( transformNames.size() < 1 )
    {
    antscout << "Missing transform names to "
             << "assemble into a composite transform"
             << std::endl;
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }
  return Assemble(CompositeName, transformNames);
}
} // namespace ants
<commit_msg>BUG: Logic for composing transforms<commit_after>#include <algorithm>
#include <iostream>
#include <sstream>
#include <iomanip>
#include "antsUtilities.h"
#include <algorithm>

#include "itkTransform.h"
#include "itkCompositeTransform.h"
#include "itkDisplacementFieldTransform.h"
#include "antsCommandLineParser.h"
#include "itkantsReadWriteTransform.h"
#include "itkTransformFactory.h"

namespace ants
{
static bool MatOffRegistered[2] = { false, false };

template <unsigned int VImageDimension>
void RegisterMatOff()
{
  if( !MatOffRegistered[VImageDimension - 2] )
    {
    MatOffRegistered[VImageDimension - 2] = true;
    // Register the matrix offset transform base class to the
    // transform factory for compatibility with the current ANTs.
    typedef itk::MatrixOffsetTransformBase<double, VImageDimension,
                                           VImageDimension> MatrixOffsetTransformType;
    itk::TransformFactory<MatrixOffsetTransformType>::RegisterTransform();
    }
}

/**
 * print the usage and exit
 */
static void PrintGenericUsageStatement()
{
  antscout << "Usage: CompositeTransformUtil --disassemble <CompositeTransform FileName>"
           << " <transform name prefix>" << std::endl
           << "or" << std::endl
           << "CompositeTransformUtil  --assemble <CompositeTransform> "
           << "<transform 1> <transform 2 > ... <transform N>" << std::endl;
}

/**
 * given a composite transform, write out all its component
 * transforms.
 */
template <unsigned int VImageDimension>
int
Disassemble(itk::TransformBase *transform, const std::string & transformName, const std::string & prefix)
{
  typedef itk::CompositeTransform<double, VImageDimension>                  CompositeTransformType;
  typedef typename CompositeTransformType::TransformTypePointer             TransformPointer;
  typedef typename itk::DisplacementFieldTransform<double, VImageDimension> DisplacementFieldTransformType;
  typedef typename DisplacementFieldTransformType::DisplacementFieldType    DisplacementFieldType;

  CompositeTransformType *composite = dynamic_cast<CompositeTransformType *>(transform);
  if( composite == 0 )
    {
    antscout << "Transform File " << transformName << " is a "
             << transform->GetNameOfClass() << " not a Composite Transform."
             << std::endl;
    return EXIT_FAILURE;
    }

  const unsigned int numTransforms = composite->GetNumberOfTransforms();
  for( unsigned int i = 0; i < numTransforms; ++i )
    {
    TransformPointer                curXfrm = composite->GetNthTransform(i);
    DisplacementFieldTransformType *dispXfrm =
      dynamic_cast<DisplacementFieldTransformType *>(curXfrm.GetPointer() );
    std::stringstream fname;
    fname << std::setfill('0') << std::setw(2) << i
          << "_" << prefix << "_"
          << curXfrm->GetNameOfClass();
    if( dispXfrm != 0 )
      {
      fname << ".nii.gz";    // if it's a displacement field transform
      }
    else
      {
      fname << ".mat";  //  .txt does not have enough precision!
      }
    itk::ants::WriteTransform<VImageDimension>(curXfrm, fname.str() );
    }
  return EXIT_SUCCESS;
}

static int Disassemble(const std::string & CompositeName,
                       const std::string & Prefix)
{
  itk::TransformBase::Pointer transform = itk::ants::ReadTransform<2>(CompositeName).GetPointer();

  if( transform.IsNull() )
    {
    transform = itk::ants::ReadTransform<3>(CompositeName).GetPointer();
    if( transform.IsNull() )
      {
      return EXIT_FAILURE; // ReadTransform prints error messages on
                           // failure.
      }
    }
  const unsigned int inDim(transform->GetInputSpaceDimension() );
  const unsigned int outDim(transform->GetOutputSpaceDimension() );
  if( inDim != outDim )
    {
    antscout << "Can't handle mixed input & output dimension: input("
             << inDim << ") output (" << outDim << ")" << std::endl;
    return EXIT_FAILURE;
    }

  switch( inDim )
    {
    case 2:
      return Disassemble<2>(transform, CompositeName, Prefix);
    case 3:
      return Disassemble<3>(transform, CompositeName, Prefix);
    default:
      antscout << "Unknown dimension " << inDim << std::endl;
      return EXIT_FAILURE;
    }
  return EXIT_SUCCESS;
}

template <unsigned int VImageDimension>
int
Assemble(const std::string & CompositeName,
         const std::vector<std::string> & transformNames,
         const typename itk::Transform<double, VImageDimension, VImageDimension>::Pointer & firstTransform)
{
  typedef itk::CompositeTransform<double, VImageDimension> CompositeTransformType;
  typedef typename CompositeTransformType::TransformType   TransformType;
  typename CompositeTransformType::Pointer composite = CompositeTransformType::New();
  composite->AddTransform(firstTransform);
  for( unsigned int i = 1; i < transformNames.size(); ++i )
    {
    typename TransformType::Pointer curXfrm = itk::ants::ReadTransform<VImageDimension>(transformNames[i]);
    if( curXfrm.IsNull() )
      {
      return EXIT_FAILURE; // ReadTransform will complain if anything goes wrong.
      }
    composite->AddTransform(curXfrm);
    }
  typename TransformType::Pointer genericXfrmPtr = composite.GetPointer();
  return itk::ants::WriteTransform<VImageDimension>(genericXfrmPtr, CompositeName);
}

static int Assemble(const std::string & CompositeName,
                    const std::vector<std::string> & transformNames)
{
    {
    itk::Transform<double, 2, 2>::Pointer FirstTransform = itk::ants::ReadTransform<2>(transformNames[0]);
    if( FirstTransform.IsNotNull() )
      {
      return Assemble<2>(CompositeName, transformNames, FirstTransform);
      }
    }
    {
    itk::Transform<double, 3, 3>::Pointer FirstTransform = itk::ants::ReadTransform<3>(transformNames[0]);
    if( FirstTransform.IsNotNull() )
      {
      return Assemble<3>(CompositeName, transformNames, FirstTransform);
      }
    }
  return EXIT_FAILURE;
}

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int CompositeTransformUtil( std::vector<std::string> args, std::ostream* out_stream = NULL )
{
  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle
  args.insert( args.begin(), "CompositeTransformUtil" );
  std::remove( args.begin(), args.end(), std::string( "" ) );
  std::remove( args.begin(), args.end(), std::string( "" ) );
  unsigned int argc = args.size();
  char* *      argv = new char *[argc + 1];
  for( unsigned int i = 0; i < argc; ++i )
    {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy( argv[i], args[i].c_str(), args[i].length() );
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
    }
  argv[argc] = 0;
  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
public:
    Cleanup_argv( char* * argv_, int argc_plus_one_ ) : argv( argv_ ), argc_plus_one( argc_plus_one_ )
    {
    }

    ~Cleanup_argv()
    {
      for( unsigned int i = 0; i < argc_plus_one; ++i )
        {
        delete[] argv[i];
        }
      delete[] argv;
    }

private:
    char* *      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv( argv, argc + 1 );

  antscout->set_stream( out_stream );
  if( argc >= 2 && ( std::string( argv[1] ) == std::string("--help") || std::string( argv[1] ) == std::string("-h") ) )
    {
    PrintGenericUsageStatement();
    return EXIT_SUCCESS;
    }

  if( argc < 2 )
    {
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }
  ++argv; --argc;
  std::string action(*argv);
  ++argv; --argc;
  if( argc == 0 )
    {
    antscout << "Missing CompositeTransformName" << std::endl;
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }

  RegisterMatOff<2>();
  RegisterMatOff<3>();

  std::string CompositeName(*argv);
  ++argv; --argc;
  if( action == "--disassemble" )
    {
    if( argc == 0 )
      {
      antscout << "Missing output transforms prefix" << std::endl;
      PrintGenericUsageStatement();
      return EXIT_FAILURE;
      }
    std::string Prefix(*argv);
    return Disassemble(CompositeName, Prefix);
    }
  else if( action != "--assemble" )
    {
    antscout << "Unknown action " << action << std::endl;
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }
  std::vector<std::string> transformNames;

  do
    {
    std::string transformName(*argv);
    ++argv; --argc;
    transformNames.push_back(transformName);
    }
  while( argc != 0 );

  if( transformNames.size() < 1 )
    {
    antscout << "Missing transform names to "
             << "assemble into a composite transform"
             << std::endl;
    PrintGenericUsageStatement();
    return EXIT_FAILURE;
    }
  return Assemble(CompositeName, transformNames);
}
} // namespace ants
<|endoftext|>


<commit_before>/*
*
*  Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library 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 for more details.
*
*  Further, this software is distributed without any warranty that it is
*  free of the rightful claim of any third person regarding infringement
*  or the like.  Any license provided herein, whether implied or
*  otherwise, applies only to this software file.  Patent licenses, if
*  any, provided herein do not apply to combinations of this program with
*  other software, or any other product whatsoever.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
*  Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
*  28359 Bremen, Germany or:
*
*  http://www.mevis.de
*
*/

#include "PythonQt_QtAll.h"

#include "PythonQt.h"

void PythonQt_init_QtGui(PyObject*);
void PythonQt_init_QtSvg(PyObject*);
void PythonQt_init_QtSql(PyObject*);
void PythonQt_init_QtNetwork(PyObject*);
void PythonQt_init_QtCore(PyObject*);
void PythonQt_init_QtWebKit(PyObject*);
void PythonQt_init_QtOpenGL(PyObject*);
void PythonQt_init_QtXml(PyObject*);
void PythonQt_init_QtXmlPatterns(PyObject*);
void PythonQt_init_QtUiTools(PyObject*);
void PythonQt_init_QtPhonon(PyObject*);

namespace PythonQt_QtAll
{
  PYTHONQT_QTALL_EXPORT void init() {
    PythonQt_init_QtCore(0);
    PythonQt_init_QtNetwork(0);
    PythonQt_init_QtGui(0);
    PythonQt_init_QtXml(0);
    PythonQt_init_QtSvg(0);
    PythonQt_init_QtSql(0);
    PythonQt_init_QtWebKit(0);
    PythonQt_init_QtOpenGL(0);
    PythonQt_init_QtUiTools(0);
    // Does not compile yet:
//    PythonQt_init_QtXmlPatterns(0);
//    PythonQt_init_QtPhonon(0);
  };
};

<commit_msg>removed phonon and xmlpatterns, which never worked<commit_after>/*
*
*  Copyright (C) 2010 MeVis Medical Solutions AG All Rights Reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library 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 for more details.
*
*  Further, this software is distributed without any warranty that it is
*  free of the rightful claim of any third person regarding infringement
*  or the like.  Any license provided herein, whether implied or
*  otherwise, applies only to this software file.  Patent licenses, if
*  any, provided herein do not apply to combinations of this program with
*  other software, or any other product whatsoever.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*
*  Contact information: MeVis Medical Solutions AG, Universitaetsallee 29,
*  28359 Bremen, Germany or:
*
*  http://www.mevis.de
*
*/

#include "PythonQt_QtAll.h"

#include "PythonQt.h"

void PythonQt_init_QtGui(PyObject*);
void PythonQt_init_QtSvg(PyObject*);
void PythonQt_init_QtSql(PyObject*);
void PythonQt_init_QtNetwork(PyObject*);
void PythonQt_init_QtCore(PyObject*);
void PythonQt_init_QtWebKit(PyObject*);
void PythonQt_init_QtOpenGL(PyObject*);
void PythonQt_init_QtXml(PyObject*);
void PythonQt_init_QtUiTools(PyObject*);

namespace PythonQt_QtAll
{
  PYTHONQT_QTALL_EXPORT void init() {
    PythonQt_init_QtCore(0);
    PythonQt_init_QtNetwork(0);
    PythonQt_init_QtGui(0);
    PythonQt_init_QtXml(0);
    PythonQt_init_QtSvg(0);
    PythonQt_init_QtSql(0);
    PythonQt_init_QtWebKit(0);
    PythonQt_init_QtOpenGL(0);
    PythonQt_init_QtUiTools(0);
  };
};

<|endoftext|>


<commit_before>#ifndef ALIGNED_BASE_HPP_INCLUDED
#define ALIGNED_BASE_HPP_INCLUDED

#include <cstddef>
#include <exception>
#include "RoundUp.hpp"
#include "IsPowerOfTwo.hpp"

#define ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE "Alignment must be a power of 2"

template<typename T, std::size_t Alignment = -1>
class AlignedBase {
	static_assert(IsPowerOfTwo<std::size_t, Alignment>::Result, ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE);
protected:
	static const std::size_t sizeOfTPaddedToAlignment = RoundUp<std::size_t, sizeof(T), Alignment>::Result;
};

template<typename T>
class AlignedBase<T, -1> {
public:
	class AlignmentException : public std::exception {
		friend class AlignedBase<T, -1>;
		AlignmentException() : std::exception(ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE) {}
	};
	AlignedBase & operator=(AlignedBase const &) = delete;
protected:
	std::size_t const sizeOfTPaddedToAlignment;
	AlignedBase(std::size_t alignment) : sizeOfTPaddedToAlignment(roundUp(sizeof(T), alignment)) {
		if (!isPowerOfTwo(alignment))
			throw new AlignmentException();
	}
};

#undef ALIGNMENT_MUST_BE_A_MULTIPLE_OF_2

#endif<commit_msg>undef typo<commit_after>#ifndef ALIGNED_BASE_HPP_INCLUDED
#define ALIGNED_BASE_HPP_INCLUDED

#include <cstddef>
#include <exception>
#include "RoundUp.hpp"
#include "IsPowerOfTwo.hpp"

#define ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE "Alignment must be a power of 2"

template<typename T, std::size_t Alignment = -1>
class AlignedBase {
	static_assert(IsPowerOfTwo<std::size_t, Alignment>::Result, ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE);
protected:
	static const std::size_t sizeOfTPaddedToAlignment = RoundUp<std::size_t, sizeof(T), Alignment>::Result;
};

template<typename T>
class AlignedBase<T, -1> {
public:
	class AlignmentException : public std::exception {
		friend class AlignedBase<T, -1>;
		AlignmentException() : std::exception(ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE) {}
	};
	AlignedBase & operator=(AlignedBase const &) = delete;
protected:
	std::size_t const sizeOfTPaddedToAlignment;
	AlignedBase(std::size_t alignment) : sizeOfTPaddedToAlignment(roundUp(sizeof(T), alignment)) {
		if (!isPowerOfTwo(alignment))
			throw new AlignmentException();
	}
};

#undef ALIGNMENT_MUST_BE_A_POWER_OF_2_ERROR_MESSAGE

#endif<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: MeasureImageSimilarity.cxx,v $
  Language:  C++
  Date:      $Date: 2009/01/05 20:09:47 $
  Version:   $Revision: 1.19 $

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "ReadWriteImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkAvantsMutualInformationRegistrationFunction.h"
#include "itkProbabilisticRegistrationFunction.h"
#include "itkCrossCorrelationRegistrationFunction.h"
// #include "itkLandmarkCrossCorrelationRegistrationFunction.h"

template <unsigned int ImageDimension>
int MeasureImageSimilarity(unsigned int argc, char *argv[])
{
  typedef float  PixelType;
  typedef itk::Vector<float,ImageDimension>         VectorType;
  typedef itk::Image<VectorType,ImageDimension>     FieldType;
  typedef itk::Image<PixelType,ImageDimension> ImageType;
  typedef itk::ImageFileWriter<ImageType> writertype;
  typedef typename ImageType::IndexType IndexType;
  typedef typename ImageType::SizeType SizeType;
  typedef typename ImageType::SpacingType SpacingType;
  typedef itk::AffineTransform<double,ImageDimension>   AffineTransformType;
  typedef itk::LinearInterpolateImageFunction<ImageType,double>  InterpolatorType1;
  typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;

  typedef itk::Image<float,2> JointHistType;
  typedef itk::ImageFileWriter<JointHistType> jhwritertype;

// get command line params
  unsigned int argct=2;
  unsigned int whichmetric = atoi(argv[argct]); argct++;
  std::string fn1 = std::string(argv[argct]); argct++;
  std::string fn2 = std::string(argv[argct]); argct++;
  std::string logfilename="";
  if (argc > argct) logfilename = std::string(argv[argct]); argct++;
  std::string imgfilename="";
  if (argc > argct) imgfilename = std::string(argv[argct]); argct++;
  double targetvalue=0;
  if (argc > argct) targetvalue = atof(argv[argct]); argct++;
  double epsilontolerance=1.e20;
  if (argc > argct) epsilontolerance = atof(argv[argct]); argct++;

  typename ImageType::Pointer image1 = NULL;
  ReadImage<ImageType>(image1, fn1.c_str());
  typename ImageType::Pointer image2 = NULL;
  ReadImage<ImageType>(image2, fn2.c_str());

/*
  typedef itk::ImageRegionIteratorWithIndex<FieldType> VIterator;
  typename FieldType::Pointer field=FieldType::New();
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->SetBufferedRegion( image1->GetLargestPossibleRegion() );
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->Allocate();
  field->SetSpacing(image1->GetSpacing());
  field->SetOrigin(image1->GetOrigin());
  VectorType zero;
  zero.Fill(0);
  VIterator vfIter2( field,  field->GetLargestPossibleRegion() );
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      vfIter2.Set(zero);
    }
*/
  typename ImageType::Pointer metricimg=ImageType::New();
  metricimg->SetRegions( image1->GetLargestPossibleRegion() );
  metricimg->Allocate();
  metricimg->SetSpacing(image1->GetSpacing());
  metricimg->SetOrigin(image1->GetOrigin());
  metricimg->SetDirection(image1->GetDirection());
  Iterator iter( metricimg,  metricimg->GetLargestPossibleRegion() );
  for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter ) iter.Set(0);

  typedef ImageType FixedImageType;
  typedef ImageType MovingImageType;
  typedef FieldType DeformationFieldType;

  // Choose the similarity metric
  typedef itk::AvantsMutualInformationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MIMetricType;
  typedef itk::CrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> CCMetricType;
  //typedef itk::LandmarkCrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MetricType;
  //typename
  typename MIMetricType::Pointer mimet=MIMetricType::New();
  typename CCMetricType::Pointer ccmet=CCMetricType::New();

//  int nbins=32;

  typename CCMetricType::RadiusType hradius;
  typename CCMetricType::RadiusType ccradius;
  ccradius.Fill(2);
  typename MIMetricType::RadiusType miradius;
  miradius.Fill(0);

//  mimet->SetDeformationField(field);
  mimet->SetFixedImage(image1);
  mimet->SetMovingImage(image2);
  mimet->SetRadius(miradius);
  mimet->SetGradientStep(1.e2);
  mimet->SetNormalizeGradient(false);

//  ccmet->SetDeformationField(field);
  ccmet->SetFixedImage(image1);
  ccmet->SetMovingImage(image2);
  ccmet->SetRadius(ccradius);
  ccmet->SetGradientStep(1.e2);
  ccmet->SetNormalizeGradient(false);

  double metricvalue=0;
  std::string metricname="";
  if (whichmetric  == 0)
    {
    hradius=miradius;
    unsigned long ct = 0;
    for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
      {
      IndexType index=iter.GetIndex();
      double fval=image1->GetPixel(index);
      double mval=image2->GetPixel(index);
      metricvalue+=fabs(fval-mval);
      metricimg->SetPixel(index,fabs(fval-mval));
     ct++;
      }
    metricvalue/=(float)ct;
    metricname="MSQ ";
    }
  else if (whichmetric == 1 ) // imagedifference
    {
    hradius=ccradius;
    metricname="CC ";
    std::cout << metricname << std::endl;
    ccmet->InitializeIteration();
    metricvalue=ccmet->ComputeCrossCorrelation()*(-1.0);
    }
  else
    {
    hradius=miradius;
    mimet->InitializeIteration();
    metricvalue=mimet->ComputeMutualInformation();
    metricname="MI ";
     }
  std::cout << fn1 << " : " << fn2 << " => " <<  metricname << metricvalue << std::endl;
  if (logfilename.length() > 3 ){
  std::ofstream logfile;
  logfile.open(logfilename.c_str(), std::ofstream::app);
  if (logfile.good())
    {
    logfile <<  fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
    }
  else std::cout << " cant open file ";
  logfile.close();

  }

  if (imgfilename.length() > 3 ){
  std::cout << "Only Implemented for MSQ " << std::endl;
  typedef itk::ImageFileWriter<ImageType> writertype;
  typename writertype::Pointer w= writertype::New();
  w->SetInput(metricimg);
  w->SetFileName(imgfilename.c_str());
  w->Write();  //  met->WriteImages();

/*
  typename MetricType::NeighborhoodType   asamIt( hradius, field,field->GetLargestPossibleRegion());
  unsigned long ct = 0;
  double totval = 0;
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      double val=0;
      asamIt.SetLocation(index);
      //      met->ComputeUpdate( asamIt,  gd);
      met->ComputeMetricAtPairB(index,  zero);
      metricimg->SetPixel(index, val);
      //if (ct % 10000 == 0)
      //		std::cout << val << " index " << index << std::endl;
      //      asamIt.SetLocation(index);
      //      totval+=met->localProbabilistic;
      ct++;
    }

  std::cout << " AvantsMI : " << totval/(double)ct << " E " <<  met->GetEnergy() <<  std::endl;
  std::cout << " write begin " << std::endl;

  std::cout << " write end " << std::endl;
*/
 }

  double diff = ((double)metricvalue - (double) targetvalue);
  std::cout << " targetvalue " << targetvalue << " metricvalue " << metricvalue << " diff " << diff << " toler " << epsilontolerance << std::endl;

  if ( diff < epsilontolerance)   return EXIT_SUCCESS;
  else return EXIT_FAILURE;

 }

int main(int argc, char *argv[])
{

  if ( argc < 3 )
    { std::cout << "Basic useage ex: " << std::endl;
    std::cout << argv[0] << " ImageDimension whichmetric image1.ext image2.ext {logfile} {outimage.ext}  {target-value}   {epsilon-tolerance}" << std::endl;
    std::cout << "  outimage (Not Implemented)  and logfile are optional  " << std::endl;
    std::cout <<" target-value and epsilon-tolerance set goals for the metric value -- if the metric value is within epsilon-tolerance of the target-value, then the test succeeds " << std::endl;
    std::cout << "  Metric 0 - MeanSquareDifference, 1 - Cross-Correlation, 2-Mutual Information  " << std::endl;
    return 1;
  }

  int metricsuccess=EXIT_FAILURE;
   // Get the image dimension
  switch( atoi(argv[1]))
   {
   case 2:
     metricsuccess=MeasureImageSimilarity<2>(argc,argv);
     break;
   case 3:
     metricsuccess=MeasureImageSimilarity<3>(argc,argv);
     break;
   default:
     std::cerr << "Unsupported dimension" << std::endl;
     exit( EXIT_FAILURE );
   }

  std::cout << " Failure? " << metricsuccess << std::endl;

  return metricsuccess;

}

<commit_msg> neg value in CC metric <commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    $RCSfile: MeasureImageSimilarity.cxx,v $
  Language:  C++
  Date:      $Date: 2009/01/05 20:09:47 $
  Version:   $Revision: 1.19 $

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "ReadWriteImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkAvantsMutualInformationRegistrationFunction.h"
#include "itkProbabilisticRegistrationFunction.h"
#include "itkCrossCorrelationRegistrationFunction.h"
// #include "itkLandmarkCrossCorrelationRegistrationFunction.h"

template <unsigned int ImageDimension>
int MeasureImageSimilarity(unsigned int argc, char *argv[])
{
  typedef float  PixelType;
  typedef itk::Vector<float,ImageDimension>         VectorType;
  typedef itk::Image<VectorType,ImageDimension>     FieldType;
  typedef itk::Image<PixelType,ImageDimension> ImageType;
  typedef itk::ImageFileWriter<ImageType> writertype;
  typedef typename ImageType::IndexType IndexType;
  typedef typename ImageType::SizeType SizeType;
  typedef typename ImageType::SpacingType SpacingType;
  typedef itk::AffineTransform<double,ImageDimension>   AffineTransformType;
  typedef itk::LinearInterpolateImageFunction<ImageType,double>  InterpolatorType1;
  typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;

  typedef itk::Image<float,2> JointHistType;
  typedef itk::ImageFileWriter<JointHistType> jhwritertype;

// get command line params
  unsigned int argct=2;
  unsigned int whichmetric = atoi(argv[argct]); argct++;
  std::string fn1 = std::string(argv[argct]); argct++;
  std::string fn2 = std::string(argv[argct]); argct++;
  std::string logfilename="";
  if (argc > argct) logfilename = std::string(argv[argct]); argct++;
  std::string imgfilename="";
  if (argc > argct) imgfilename = std::string(argv[argct]); argct++;
  double targetvalue=0;
  if (argc > argct) targetvalue = atof(argv[argct]); argct++;
  double epsilontolerance=1.e20;
  if (argc > argct) epsilontolerance = atof(argv[argct]); argct++;

  typename ImageType::Pointer image1 = NULL;
  ReadImage<ImageType>(image1, fn1.c_str());
  typename ImageType::Pointer image2 = NULL;
  ReadImage<ImageType>(image2, fn2.c_str());

/*
  typedef itk::ImageRegionIteratorWithIndex<FieldType> VIterator;
  typename FieldType::Pointer field=FieldType::New();
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->SetBufferedRegion( image1->GetLargestPossibleRegion() );
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->Allocate();
  field->SetSpacing(image1->GetSpacing());
  field->SetOrigin(image1->GetOrigin());
  VectorType zero;
  zero.Fill(0);
  VIterator vfIter2( field,  field->GetLargestPossibleRegion() );
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      vfIter2.Set(zero);
    }
*/
  typename ImageType::Pointer metricimg=ImageType::New();
  metricimg->SetRegions( image1->GetLargestPossibleRegion() );
  metricimg->Allocate();
  metricimg->SetSpacing(image1->GetSpacing());
  metricimg->SetOrigin(image1->GetOrigin());
  metricimg->SetDirection(image1->GetDirection());
  Iterator iter( metricimg,  metricimg->GetLargestPossibleRegion() );
  for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter ) iter.Set(0);

  typedef ImageType FixedImageType;
  typedef ImageType MovingImageType;
  typedef FieldType DeformationFieldType;

  // Choose the similarity metric
  typedef itk::AvantsMutualInformationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MIMetricType;
  typedef itk::CrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> CCMetricType;
  //typedef itk::LandmarkCrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DeformationFieldType> MetricType;
  //typename
  typename MIMetricType::Pointer mimet=MIMetricType::New();
  typename CCMetricType::Pointer ccmet=CCMetricType::New();

//  int nbins=32;

  typename CCMetricType::RadiusType hradius;
  typename CCMetricType::RadiusType ccradius;
  ccradius.Fill(2);
  typename MIMetricType::RadiusType miradius;
  miradius.Fill(0);

//  mimet->SetDeformationField(field);
  mimet->SetFixedImage(image1);
  mimet->SetMovingImage(image2);
  mimet->SetRadius(miradius);
  mimet->SetGradientStep(1.e2);
  mimet->SetNormalizeGradient(false);

//  ccmet->SetDeformationField(field);
  ccmet->SetFixedImage(image1);
  ccmet->SetMovingImage(image2);
  ccmet->SetRadius(ccradius);
  ccmet->SetGradientStep(1.e2);
  ccmet->SetNormalizeGradient(false);

  double metricvalue=0;
  std::string metricname="";
  if (whichmetric  == 0)
    {
    hradius=miradius;
    unsigned long ct = 0;
    for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
      {
      IndexType index=iter.GetIndex();
      double fval=image1->GetPixel(index);
      double mval=image2->GetPixel(index);
      metricvalue+=fabs(fval-mval);
      metricimg->SetPixel(index,fabs(fval-mval));
     ct++;
      }
    metricvalue/=(float)ct;
    metricname="MSQ ";
    }
  else if (whichmetric == 1 ) // imagedifference
    {
    hradius=ccradius;
    metricname="CC ";
    std::cout << metricname << std::endl;
    ccmet->InitializeIteration();
    metricvalue=ccmet->ComputeCrossCorrelation()*(1.0);
    }
  else
    {
    hradius=miradius;
    mimet->InitializeIteration();
    metricvalue=mimet->ComputeMutualInformation();
    metricname="MI ";
     }
  std::cout << fn1 << " : " << fn2 << " => " <<  metricname << metricvalue << std::endl;
  if (logfilename.length() > 3 ){
  std::ofstream logfile;
  logfile.open(logfilename.c_str(), std::ofstream::app);
  if (logfile.good())
    {
    logfile <<  fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
    }
  else std::cout << " cant open file ";
  logfile.close();

  }

  if (imgfilename.length() > 3 ){
  std::cout << "Only Implemented for MSQ " << std::endl;
  typedef itk::ImageFileWriter<ImageType> writertype;
  typename writertype::Pointer w= writertype::New();
  w->SetInput(metricimg);
  w->SetFileName(imgfilename.c_str());
  w->Write();  //  met->WriteImages();

/*
  typename MetricType::NeighborhoodType   asamIt( hradius, field,field->GetLargestPossibleRegion());
  unsigned long ct = 0;
  double totval = 0;
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      double val=0;
      asamIt.SetLocation(index);
      //      met->ComputeUpdate( asamIt,  gd);
      met->ComputeMetricAtPairB(index,  zero);
      metricimg->SetPixel(index, val);
      //if (ct % 10000 == 0)
      //		std::cout << val << " index " << index << std::endl;
      //      asamIt.SetLocation(index);
      //      totval+=met->localProbabilistic;
      ct++;
    }

  std::cout << " AvantsMI : " << totval/(double)ct << " E " <<  met->GetEnergy() <<  std::endl;
  std::cout << " write begin " << std::endl;

  std::cout << " write end " << std::endl;
*/
 }

  double diff = ((double)metricvalue - (double) targetvalue);
  std::cout << " targetvalue " << targetvalue << " metricvalue " << metricvalue << " diff " << diff << " toler " << epsilontolerance << std::endl;

  if ( diff < epsilontolerance)   return EXIT_SUCCESS;
  else return EXIT_FAILURE;

 }

int main(int argc, char *argv[])
{

  if ( argc < 3 )
    { std::cout << "Basic useage ex: " << std::endl;
    std::cout << argv[0] << " ImageDimension whichmetric image1.ext image2.ext {logfile} {outimage.ext}  {target-value}   {epsilon-tolerance}" << std::endl;
    std::cout << "  outimage (Not Implemented)  and logfile are optional  " << std::endl;
    std::cout <<" target-value and epsilon-tolerance set goals for the metric value -- if the metric value is within epsilon-tolerance of the target-value, then the test succeeds " << std::endl;
    std::cout << "  Metric 0 - MeanSquareDifference, 1 - Cross-Correlation, 2-Mutual Information  " << std::endl;
    return 1;
  }

  int metricsuccess=EXIT_FAILURE;
   // Get the image dimension
  switch( atoi(argv[1]))
   {
   case 2:
     metricsuccess=MeasureImageSimilarity<2>(argc,argv);
     break;
   case 3:
     metricsuccess=MeasureImageSimilarity<3>(argc,argv);
     break;
   default:
     std::cerr << "Unsupported dimension" << std::endl;
     exit( EXIT_FAILURE );
   }

  std::cout << " Failure? " << metricsuccess << std::endl;

  return metricsuccess;

}

<|endoftext|>


<commit_before>/*
    This file is part of the MinSG library extension LoaderCOLLADA.
    Copyright (C) 2013 Benjamin Eikel <benjamin@eikel.org>
    Copyright (C) 2012 Lukas Kopecki

    This library is subject to the terms of the Mozilla Public License, v. 2.0.
    You should have received a copy of the MPL along with this library; see the
    file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_LOADERCOLLADA

#include "LoaderCOLLADA.h"
#include "Writer.h"
#include "../../SceneManagement/SceneDescription.h"
#include <Util/IO/FileName.h>

COMPILER_WARN_PUSH
COMPILER_WARN_OFF_GCC(-Wold-style-cast)
COMPILER_WARN_OFF_GCC(-Wzero-as-null-pointer-constant)
COMPILER_WARN_OFF_GCC(-Wswitch-default)
COMPILER_WARN_OFF_CLANG(-W#warnings)
#include <COLLADASaxFWLIError.h>
#include <COLLADASaxFWLIErrorHandler.h>
#include <COLLADASaxFWLLoader.h>
#include <COLLADASaxFWLPrerequisites.h>
#include <COLLADAFWRoot.h>
COMPILER_WARN_POP

#include <string>
#include <functional>

#include <Util/Macros.h>
#include <Util/Timer.h>

namespace MinSG {
namespace LoaderCOLLADA {

class ErrorHandler : public COLLADASaxFWL::IErrorHandler {
	private:
		std::ostream & out;

	public:
		ErrorHandler(std::ostream & outStream) :
			out(outStream) {
		}
		virtual ~ErrorHandler() {
		}

		bool handleError(const COLLADASaxFWL::IError * error) override {
			switch(error->getSeverity()) {
				case COLLADASaxFWL::IError::SEVERITY_CRITICAL:
					out << "Critical";
					break;
				case COLLADASaxFWL::IError::SEVERITY_ERROR_NONCRITICAL:
					out << "Non-critical";
					break;
				default:
					break;
			}
			out << ' ';
			switch(error->getErrorClass()) {
				case COLLADASaxFWL::IError::ERROR_SAXPARSER:
					out << "SaxParser";
					break;
				case COLLADASaxFWL::IError::ERROR_SAXFWL:
					out << "SaxFWL";
					break;
				default:
					out << "Unknown";
					break;
			}
			out << error->getFullErrorMessage() << '\n';
			// Continue loading.
			return true;
		}
};

static std::string getVersionString(const COLLADASaxFWL::COLLADAVersion & version) {
	switch(version) {
		case COLLADASaxFWL::COLLADAVersion::COLLADA_14:
			return "1.4";
		case COLLADASaxFWL::COLLADAVersion::COLLADA_15:
			return "1.5";
		case COLLADASaxFWL::COLLADAVersion::COLLADA_UNKNOWN:
		default:
			break;
	}
	return "Unknown";
}

const SceneManagement::DescriptionMap * loadScene(const Util::FileName & fileName, bool invertTransparency) {

	Util::Timer timer;
	timer.reset();

	ErrorHandler errorHandler(std::cerr);
	COLLADASaxFWL::Loader loader(&errorHandler);

	Writer & writer = Writer::instance();
	writer.beginLoadingProcess();
	writer.setInvertTransparency(invertTransparency);

	COLLADAFW::Root root(&loader, &writer);

	const bool success = root.loadDocument(fileName.getPath());
	if(!success) {
		return nullptr;
	}

	timer.stop();

	std::cout << "Loaded COLLADA " << getVersionString(loader.getCOLLADAVersion()) << " document in " << timer.getSeconds() << " seconds." << std::endl;

	auto scene = writer.releaseSceneDescription();
	writer.endLoadingProcess();
	return scene;
}

}
}

#endif /* MINSG_EXT_LOADERCOLLADA */
<commit_msg>compile fix<commit_after>/*
    This file is part of the MinSG library extension LoaderCOLLADA.
    Copyright (C) 2013 Benjamin Eikel <benjamin@eikel.org>
    Copyright (C) 2012 Lukas Kopecki

    This library is subject to the terms of the Mozilla Public License, v. 2.0.
    You should have received a copy of the MPL along with this library; see the
    file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifdef MINSG_EXT_LOADERCOLLADA

#include <iostream>

#include "LoaderCOLLADA.h"
#include "Writer.h"
#include "../../SceneManagement/SceneDescription.h"
#include <Util/IO/FileName.h>

COMPILER_WARN_PUSH
COMPILER_WARN_OFF_GCC(-Wold-style-cast)
COMPILER_WARN_OFF_GCC(-Wzero-as-null-pointer-constant)
COMPILER_WARN_OFF_GCC(-Wswitch-default)
COMPILER_WARN_OFF_CLANG(-W#warnings)
#include <COLLADASaxFWLIError.h>
#include <COLLADASaxFWLIErrorHandler.h>
#include <COLLADASaxFWLLoader.h>
#include <COLLADASaxFWLPrerequisites.h>
#include <COLLADAFWRoot.h>
COMPILER_WARN_POP

#include <string>
#include <functional>

#include <Util/Macros.h>
#include <Util/Timer.h>

namespace MinSG {
namespace LoaderCOLLADA {

class ErrorHandler : public COLLADASaxFWL::IErrorHandler {
	private:
		std::ostream & out;

	public:
		ErrorHandler(std::ostream & outStream) :
			out(outStream) {
		}
		virtual ~ErrorHandler() {
		}

		bool handleError(const COLLADASaxFWL::IError * error) override {
			switch(error->getSeverity()) {
				case COLLADASaxFWL::IError::SEVERITY_CRITICAL:
					out << "Critical";
					break;
				case COLLADASaxFWL::IError::SEVERITY_ERROR_NONCRITICAL:
					out << "Non-critical";
					break;
				default:
					break;
			}
			out << ' ';
			switch(error->getErrorClass()) {
				case COLLADASaxFWL::IError::ERROR_SAXPARSER:
					out << "SaxParser";
					break;
				case COLLADASaxFWL::IError::ERROR_SAXFWL:
					out << "SaxFWL";
					break;
				default:
					out << "Unknown";
					break;
			}
			out << error->getFullErrorMessage() << '\n';
			// Continue loading.
			return true;
		}
};

static std::string getVersionString(const COLLADASaxFWL::COLLADAVersion & version) {
	switch(version) {
		case COLLADASaxFWL::COLLADAVersion::COLLADA_14:
			return "1.4";
		case COLLADASaxFWL::COLLADAVersion::COLLADA_15:
			return "1.5";
		case COLLADASaxFWL::COLLADAVersion::COLLADA_UNKNOWN:
		default:
			break;
	}
	return "Unknown";
}

const SceneManagement::DescriptionMap * loadScene(const Util::FileName & fileName, bool invertTransparency) {

	Util::Timer timer;
	timer.reset();

	ErrorHandler errorHandler(std::cerr);
	COLLADASaxFWL::Loader loader(&errorHandler);

	Writer & writer = Writer::instance();
	writer.beginLoadingProcess();
	writer.setInvertTransparency(invertTransparency);

	COLLADAFW::Root root(&loader, &writer);

	const bool success = root.loadDocument(fileName.getPath());
	if(!success) {
		return nullptr;
	}

	timer.stop();

	std::cout << "Loaded COLLADA " << getVersionString(loader.getCOLLADAVersion()) << " document in " << timer.getSeconds() << " seconds." << std::endl;

	auto scene = writer.releaseSceneDescription();
	writer.endLoadingProcess();
	return scene;
}

}
}

#endif /* MINSG_EXT_LOADERCOLLADA */
<|endoftext|>


<commit_before>/*!
*	@file	CurvatureFlow.cpp
*	@brief	Implementation of a curvature flow algorithm
*/

#include "CurvatureFlow.h"

namespace psalm
{

/*!
*	Given an input mesh, calculates the curvature operator matrix for this
*	mesh. The matrix will be a _sparse_ matrix, hence the need for handling
*	it via boost.
*
*	@param	input_mesh Mesh to be processed
*	@return	Sparse matrix describing the curvature operator
*/

boost::numeric::ublas::mapped_matrix<double> CurvatureFlow::calc_curvature_operator(mesh& input_mesh)
{
	using namespace boost::numeric::ublas;
	mapped_matrix<double> K(input_mesh.num_vertices(), input_mesh.num_vertices()); // K as in "Kurvature"...

	// We iterate over all faces and calculate the contributions of each
	// vertex of the face to the corresponding entry of the matrix

	for(size_t i = 0; i < input_mesh.num_faces(); i++)
	{
		face* f = input_mesh.get_face(i);
		for(size_t j = 0; j < f->num_vertices(); j++)
		{
			vertex* v = f->get_vertex(j);
			std::vector<const vertex*> neighbours = v->get_neighbours();

			// FIXME: Used to update the correct matrix entries
			// below. This assumes that the IDs have been allocated
			// sequentially.
			size_t cur_id = v->get_id();

			// Find "opposing angles" for all neighbours; these are
			// the $\alpha_{ij}$ and $\beta_{ij}$ values used for
			// calculating the discrete curvature

			for(size_t k = 0; k < neighbours.size(); k++)
			{
				std::pair<double, double> angles = v->find_opposite_angles(neighbours[k]);
				if(angles.first >= 0.0 && angles.second >= 0.0)
				{
					// calculate contribution to matrix entries

					double contribution = 1.0/tan(angles.first) + 1.0/tan(angles.second);

					K(cur_id, cur_id)			+= contribution;
					K(cur_id, neighbours[k]->get_id())	-= contribution;
				}
			}
		}
	}

	// Scale the ith row of the matrix by the Voronoi area around the ith vertex

	for(size_t i = 0; i < input_mesh.num_vertices(); i++)
	{
		double area = input_mesh.get_vertex(i)->calc_voronoi_area();
		if(area < 2*std::numeric_limits<double>::epsilon())
		{
			// skip on error or upon encountering a Voronoi area
			// that is too small
			continue;
		}

		for(size_t j = 0; j < input_mesh.num_vertices(); j++)
		{
			if(K(i,j) != 0)
				K(i,j) *= area;
		}
	}

	return(K);
}

} // end of namespace "psalm"
<commit_msg>Added preliminary version of `CurvatureFlow`<commit_after>/*!
*	@file	CurvatureFlow.cpp
*	@brief	Implementation of a curvature flow algorithm
*/

#include "CurvatureFlow.h"

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/io.hpp>

namespace psalm
{

/*!
*	Applies the curvature flow algorithm to the vertices of a given mesh.
*	The size of timesteps needs to be set before. The input mesh is
*	irreversibly changed by this operation.
*
*	@param	input_mesh Mesh on which the algorithm works.
*	@return	false if an error occurred, else true
*/

bool CurvatureFlow::apply_to(mesh& input_mesh)
{
	using namespace boost::numeric::ublas;

	size_t n = input_mesh.num_vertices();
	if(n == 0)
		return(true); // silently ignore empty meshes

	// Stores x,y,z components of the vertices in the mesh
	vector<double> X(n);
	vector<double> Y(n);
	vector<double> Z(n);

	// Fill vector with position data
	for(size_t i = 0; i < n; i++)
	{
		const v3ctor& pos = input_mesh.get_vertex(i)->get_position();

		X[i] = pos[0];
		Y[i] = pos[1];
		Z[i] = pos[2];
	}

	// Prepare for "solving" the linear system (for now, this is something
	// akin to the explicit Euler method)

	mapped_matrix<double> M(n, n);	// transformed matrix for the solving
					// process, i.e. id - dt*K, where K is
					// the matrix of the curvature operator

	// FIXME: Should be user-configurable
	double dt = 0.01;

	M = identity_matrix<double>(n, n) - dt*calc_curvature_operator(input_mesh);

	// Solve x,y,z components independently. This is _hellishly_ slow, but
	// sufficient for small meshes.

	vector<double> new_X = prod(M, X);
	vector<double> new_Y = prod(M, Y);
	vector<double> new_Z = prod(M, Z);

	for(size_t i = 0; i < n; i++)
		input_mesh.get_vertex(i)->set_position(new_X[i], new_Y[i], new_Z[i]);

	return(true);
}

/*!
*	Given an input mesh, calculates the curvature operator matrix for this
*	mesh. The matrix will be a _sparse_ matrix, hence the need for handling
*	it via boost.
*
*	@param	input_mesh Mesh to be processed
*	@return	Sparse matrix describing the curvature operator
*/

boost::numeric::ublas::mapped_matrix<double> CurvatureFlow::calc_curvature_operator(mesh& input_mesh)
{
	using namespace boost::numeric::ublas;
	mapped_matrix<double> K(input_mesh.num_vertices(), input_mesh.num_vertices()); // K as in "Kurvature"...

	// We iterate over all faces and calculate the contributions of each
	// vertex of the face to the corresponding entry of the matrix

	for(size_t i = 0; i < input_mesh.num_faces(); i++)
	{
		face* f = input_mesh.get_face(i);
		for(size_t j = 0; j < f->num_vertices(); j++)
		{
			vertex* v = f->get_vertex(j);
			std::vector<const vertex*> neighbours = v->get_neighbours();

			// FIXME: Used to update the correct matrix entries
			// below. This assumes that the IDs have been allocated
			// sequentially.
			size_t cur_id = v->get_id();

			// Find "opposing angles" for all neighbours; these are
			// the $\alpha_{ij}$ and $\beta_{ij}$ values used for
			// calculating the discrete curvature

			for(size_t k = 0; k < neighbours.size(); k++)
			{
				std::pair<double, double> angles = v->find_opposite_angles(neighbours[k]);
				if(angles.first >= 0.0 && angles.second >= 0.0)
				{
					// calculate contribution to matrix entries

					double contribution = 1.0/tan(angles.first) + 1.0/tan(angles.second);

					K(cur_id, cur_id)			+= contribution;
					K(cur_id, neighbours[k]->get_id())	-= contribution;
				}
			}
		}
	}

	// Scale the ith row of the matrix by the Voronoi area around the ith vertex

	for(size_t i = 0; i < input_mesh.num_vertices(); i++)
	{
		double area = input_mesh.get_vertex(i)->calc_voronoi_area();
		if(area < 2*std::numeric_limits<double>::epsilon())
		{
			// skip on error or upon encountering a Voronoi area
			// that is too small
			continue;
		}

		for(size_t j = 0; j < input_mesh.num_vertices(); j++)
		{
			if(K(i,j) != 0)
				K(i,j) *= area;
		}
	}

	return(K);
}

} // end of namespace "psalm"
<|endoftext|>