Exemplo n.º 1
0
bool Part::readProperties(XmlReader& e)
      {
      const QStringRef& tag(e.name());
      if (tag == "Staff") {
            Staff* staff = new Staff(score());
            staff->setPart(this);
            score()->staves().push_back(staff);
            _staves.push_back(staff);
            staff->read(e);
            }
      else if (tag == "Instrument") {
            Instrument* instr = new Instrument;
            instr->read(e, this);
            setInstrument(instr, -1);
            }
      else if (tag == "name")
            instrument()->setLongName(e.readElementText());
      else if (tag == "shortName")
            instrument()->setShortName(e.readElementText());
      else if (tag == "trackName")
            _partName = e.readElementText();
      else if (tag == "show")
            _show = e.readInt();
      else
            return false;
      return true;
      }
Exemplo n.º 2
0
void concurrency_instrumentationt::instrument(
  goto_programt &goto_program,
  const is_threadedt &is_threaded)
{
  for(goto_programt::instructionst::iterator
      it=goto_program.instructions.begin();
      it!=goto_program.instructions.end();
      it++)
  {
    if(it->is_assign())
    {
      code_assignt &code=to_code_assign(it->code);
      instrument(code.rhs());
    }
    else if(it->is_assume() || it->is_assert() || it->is_goto())
      instrument(it->guard);
    else if(it->is_function_call())
    {
      code_function_callt &code=to_code_function_call(it->code);
      instrument(code.function());

      //instrument(code.lhs(), LHS);
      Forall_expr(it, code.arguments())
        instrument(*it);
    }
  }
}
Exemplo n.º 3
0
void Part::read(XmlReader& e)
      {
      while (e.readNextStartElement()) {
            const QStringRef& tag(e.name());
            if (tag == "Staff") {
                  Staff* staff = new Staff(_score);
                  staff->setPart(this);
                  _score->staves().push_back(staff);
                  _staves.push_back(staff);
                  staff->read(e);
                  }
            else if (tag == "Instrument") {
                  Instrument* instr = new Instrument;
                  instr->read(e);
                  setInstrument(instr, -1);
                  }
            else if (tag == "name")
                  instrument()->setLongName(e.readElementText());
            else if (tag == "shortName")
                  instrument()->setShortName(e.readElementText());
            else if (tag == "trackName")
                  _partName = e.readElementText();
            else if (tag == "show")
                  _show = e.readInt();
            else
                  e.unknown();
            }
      if (_partName.isEmpty())
            _partName = instrument()->trackName();
      }
/**
 * \brief Comparison operator for GuiderDescriptor objects
 */
bool	GuiderDescriptor::operator<(const GuiderDescriptor& other) const {
	if (name() < other.name()) {
		return true;
	}
	if (name() > other.name()) {
		return false;
	}
	if (instrument() < other.instrument()) {
		return true;
	}
	if (instrument() > other.instrument()) {
		return false;
	}
	if (ccd() < other.ccd()) {
		return true;
	}
	if (ccd() > other.ccd()) {
		return false;
	}
	if (guideport() < other.guideport()) {
		return true;
	}
	if (guideport() > other.guideport()) {
		return false;
	}
	return adaptiveoptics() < other.adaptiveoptics();
}
bool CombinationEnumerator::findInstrument(Instrumentv2* ref_instrument, double epsilon, mat& instrument_points)
{
	if (points->n_rows < combination_size) return false;
	candidates.clear();
	ref_instrument->access_mutex.lock();
	Instrumentv2 instrument(*ref_instrument);
	ref_instrument->access_mutex.unlock();
	this->ref_instrument = &instrument;
	this->epsilon = epsilon;
	found_points = zeros<mat>(combination_size, 3);
	combination = zeros<mat>(combination_size,3);
	combination_row = 0;
	enumerateCombinations(0,combination_size);
	bool isFound = false;
	//filter found points
	if (candidates.size() > 0){
		isFound = true;
		auto best_iter = candidates.begin();
		instrument_points = best_iter->second;

		//check distances

	}

	//if (result) instrument_points = found_points;
	return isFound;
}
void	InstrumentTest::testInstrument() {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testInstrument() begin");
	ConfigurationPtr	config = Configuration::get(dbfilename);
	Database	database = config->database();

	// create an instrument
	Instrument	instrument(database, "BLUBB");

	// add a few components
	InstrumentComponentPtr	camera = InstrumentComponentPtr(
		new InstrumentComponentDirect(DeviceName::Camera,
			DeviceName("camera:simulator/camera"), 7, "localhost"));
	instrument.add(camera);
	InstrumentComponentPtr	ccd = InstrumentComponentPtr(
		new InstrumentComponentDerived(DeviceName::Ccd,
			instrument, DeviceName::Camera, 5));
	instrument.add(ccd);

	// check instrument
	CPPUNIT_ASSERT(instrument.name() == "BLUBB");

	// has method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'has' method");
	CPPUNIT_ASSERT(instrument.has(DeviceName::Camera));
	CPPUNIT_ASSERT(instrument.has(DeviceName::Ccd));

	// component_type method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'component_type' method");
	CPPUNIT_ASSERT(instrument.component_type(DeviceName::Camera)
		== InstrumentComponent::direct);
	CPPUNIT_ASSERT(instrument.component_type(DeviceName::Ccd)
		== InstrumentComponent::derived);

	// devicename method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'devicename' method");
	CPPUNIT_ASSERT(instrument.devicename(DeviceName::Camera)
		== DeviceName("camera:simulator/camera"));
	debug(LOG_DEBUG, DEBUG_LOG, 0, "ccd device: %s",
		instrument.devicename(DeviceName::Ccd).toString().c_str());
	CPPUNIT_ASSERT(instrument.devicename(DeviceName::Ccd)
		== DeviceName("camera:simulator/camera"));

	// name method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'name' method");
	debug(LOG_DEBUG, DEBUG_LOG, 0, "name(camera) = %s",
		instrument.name(DeviceName::Camera).c_str());
	CPPUNIT_ASSERT(instrument.name(DeviceName::Camera)
		== DeviceName("camera:simulator/camera").toString());

	debug(LOG_DEBUG, DEBUG_LOG, 0, "name(ccd) = %s",
		instrument.name(DeviceName::Ccd).c_str());
	CPPUNIT_ASSERT(instrument.name(DeviceName::Ccd) == "camera");

	// unit method
	debug(LOG_DEBUG, DEBUG_LOG, 0, "test 'unit' method");
	CPPUNIT_ASSERT(instrument.unit(DeviceName::Camera) == 7);
	CPPUNIT_ASSERT(instrument.unit(DeviceName::Ccd) == 5);
	
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testInstrument() end");
}
Exemplo n.º 7
0
void Part::setMidiChannel(int ch, int port, int tick)
      {
      Channel* channel = instrument(tick)->channel(0);
      if (channel->channel == -1) {
            // Add new mapping
            MidiMapping mm;
            mm.part = this;
            mm.articulation = channel;
            mm.channel = -1;
            mm.port = -1;
            if (ch != -1)
                  mm.channel = ch;
            if (port != -1)
                  mm.port = port;
            channel->channel = masterScore()->midiMapping()->size();
            masterScore()->midiMapping()->append(mm);
            }
      else {
            // Update existing mapping
            if (channel->channel >= masterScore()->midiMapping()->size()) {
                  qDebug()<<"Can't' set midi channel: midiMapping is empty!";
                  return;
                  }

            if (ch != -1)
                  masterScore()->midiMapping(channel->channel)->channel = ch;
            if (port != -1)
                  masterScore()->midiMapping(channel->channel)->port = port;
            masterScore()->midiMapping(channel->channel)->part = this;
            }
      }
Exemplo n.º 8
0
bool Part::setProperty(P_ID id, const QVariant& property)
      {
      switch (id) {
            case P_ID::VISIBLE:
                  setShow(property.toBool());
                  break;
            case P_ID::USE_DRUMSET:
                  instrument()->setUseDrumset(property.toBool());
                  break;
            case P_ID::PART_VOLUME:
                  setVolume(property.toInt());
                  break;
            case P_ID::PART_MUTE:
                  setMute(property.toBool());
                  break;
            case P_ID::PART_PAN:
                  setPan(property.toInt());
                  break;
            case P_ID::PART_REVERB:
                  setReverb(property.toInt());
                  break;
            case P_ID::PART_CHORUS:
                  setChorus(property.toInt());
                  break;
            default:
                  qDebug("Part::setProperty: unknown id %d", int(id));
                  break;
            }
      score()->setLayoutAll();
      return true;
      }
Exemplo n.º 9
0
/***********************************************************************//**
 * @brief Print multi-wavelength information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing multi-wavelength information.
 ***************************************************************************/
std::string GMWLObservation::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GMWLObservation ===");

        // Append information
        result.append("\n"+gammalib::parformat("Name")+name());
        result.append("\n"+gammalib::parformat("Identifier")+id());
        result.append("\n"+gammalib::parformat("Instrument")+instrument());
        result.append("\n"+gammalib::parformat("Statistics")+statistics());

        // EXPLICIT: Append events
        if (chatter >=  EXPLICIT) {
            if (m_events != NULL) {
                result.append("\n"+m_events->print(chatter));
            }
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
Exemplo n.º 10
0
 void operator() ( Buffer< SampleType > &_buffer ) {
   if ( is_end ) {
     fillZero ( _buffer );
     return;
   }
   double time = instrument.getGlobalTime();
   while ( !release_stack.empty() && time - release_stack.top().first >= -0.00001f ) {
     instrument.noteOff ( release_stack.top().second );
     release_stack.pop();
   }
   while ( time - current_score->pos >= -0.00001f ) {
     if ( current_score->length == 0.0f ) {
       is_end = true;
       fillZero ( _buffer );
       return;
     }
     else {
       std::pair< double, int > temp;
       temp.first = current_score->pos + current_score->length;
       temp.second = instrument.noteOn ( current_score->note, exp2f ( ( current_score->touch - 1.0f ) * 10.0f ) );
       release_stack.push ( temp );
     }
     current_score++;
   }
   instrument ( _buffer );
 }
Exemplo n.º 11
0
//--------------------------------------------------------------
void testApp::setupLines() {
    
    // First of all, clear out the vectors (in case of reset).
    // First the lineLists inside the dancerList...
    for ( int i = 0; i < dancerList.size(); i++) {
        dancerList[ i ].lineList.clear();
    }
    // ...then the dancerList itself.
    dancerList.clear();
    
    // Maintenance
    ofSetVerticalSync( true );
    ofSetFrameRate( 60 );
    ofSetCircleResolution( 100 );
    
    // May want to change this to a gradient or something else.
    ofBackground( 0 );
    
    breath = 0;
    breathRad = 50;
    noiseBreath = true;
    
    // Create Dancers, feed in a pos and vel, and add them to the vector.
    for ( int i = 0; i < NUMDANCERS; i++ ) {
        Dancer instrument( ofVec2f( ofRandomWidth(), ofRandomHeight() ),  ofVec2f( ofRandom( -0.5, 0.5 ), ofRandom( -0.5, 0.5 ) ) );
        dancerList.push_back( instrument );
    }
}
Exemplo n.º 12
0
void Part::setMidiProgram(int program, int bank)
      {
      Channel* c = instrument()->channel(0);
      c->program = program;
      c->bank    = bank;
      c->updateInitList();
//      instrument()->setChannel(0, c);
      }
Exemplo n.º 13
0
/***********************************************************************//**
 * @brief Return model value and (optionally) gradient
 *
 * @param[in] models Model descriptor.
 * @param[in] event Observed event.
 * @param[out] gradient Pointer to gradient vector (optional).
 *
 * @exception GException::gradient_par_mismatch
 *            Dimension of gradient vector mismatches number of parameters.
 *
 * Implements generic model and gradient evaluation for an observation. The
 * model gives the probability for an event to occur with a given instrument
 * direction, at a given energy and at a given time. The gradient is the
 * parameter derivative of this probability. If NULL is passed for the
 * gradient vector, then gradients will not be computed.
 *
 * The method will only operate on models for which the list of instruments
 * and observation identifiers matches those of the observation. Models that
 * do not match will be skipped.
 ***************************************************************************/
double GObservation::model(const GModels& models, const GEvent& event,
                           GVector* gradient) const
{
    // Verify that gradient vector and models have the same dimension
    #if defined(G_RANGE_CHECK)
    if (gradient != NULL) {
        if (models.npars() != gradient->size()) {
            throw GException::gradient_par_mismatch(G_MODEL, 
                                                    gradient->size(),
                                                    models.npars());
        }
    }
    #endif

    // Initialise
    double model = 0.0;    // Reset model value
    int    igrad = 0;      // Reset gradient counter

    // If gradient is available then reset gradient vector elements to 0
    if (gradient != NULL) {
        (*gradient) = 0.0;
    }

    // Loop over models
    for (int i = 0; i < models.size(); ++i) {

        // Get model pointer. Continue only if pointer is valid
        const GModel* mptr = models[i];
        if (mptr != NULL) {

            // Continue only if model applies to specific instrument and
            // observation identifier
            if (mptr->isvalid(instrument(), id())) {

                // Compute value and add to model
                model += mptr->eval_gradients(event, *this);

                // Optionally determine model gradients
                if (gradient != NULL) {
                    for (int k = 0; k < mptr->size(); ++k) {
                        (*gradient)[igrad+k] = model_grad(*mptr, event, k);
                    }
                }

            } // endif: model component was valid for instrument

            // Increment parameter counter for gradients
            igrad += mptr->size();

        } // endif: model was valid

    } // endfor: Looped over models

    // Return
    return model;
}
Exemplo n.º 14
0
/***********************************************************************//**
 * @brief Return total number (and optionally gradient) of predicted counts
 *        for all models
 *
 * @param[in] models Models.
 * @param[out] gradient Model parameter gradients (optional).
 *
 * @exception GException::gradient_par_mismatch
 *            Dimension of gradient vector mismatches number of parameters.
 *
 * Returns the total number of predicted counts within the analysis region.
 * If NULL is passed for the gradient vector then gradients will not be
 * computed.
 *
 * The method will only operate on models for which the list of instruments
 * and observation identifiers matches those of the observation. Models that
 * do not match will be skipped.
 ***************************************************************************/
double GObservation::npred(const GModels& models, GVector* gradient) const
{
    // Verify that gradient vector and models have the same dimension
    #if defined(G_RANGE_CHECK)
    if (gradient != NULL) {
        if (models.npars() != gradient->size()) {
            throw GException::gradient_par_mismatch(G_MODEL, 
                                                    gradient->size(),
                                                    models.npars());
        }
    }
    #endif

    // Initialise
    double npred = 0.0;    // Reset predicted number of counts
    int    igrad = 0;      // Reset gradient counter

    // If gradient is available then reset gradient vector elements to 0
    if (gradient != NULL) {
        (*gradient) = 0.0;
    }

    // Loop over models
    for (int i = 0; i < models.size(); ++i) {

        // Get model pointer. Continue only if pointer is valid
        const GModel* mptr = models[i];
        if (mptr != NULL) {

            // Continue only if model applies to specific instrument and
            // observation identifier
            if (mptr->isvalid(instrument(), id())) {

                // Determine Npred for model
                npred += npred_temp(*mptr);

                // Optionally determine Npred gradients
                if (gradient != NULL) {
                    for (int k = 0; k < mptr->size(); ++k) {
                        (*gradient)[igrad+k] = npred_grad(*mptr, k);
                    }
                }

            } // endif: model component was valid for instrument

            // Increment parameter counter for gradient
            igrad += mptr->size();

        } // endif: model was valid

    } // endfor: Looped over models

    // Return prediction
    return npred;
}
Exemplo n.º 15
0
void bandBar::setup(xmlParse * config)
{
    clearBut.setTitle("clear blocks");
    clearBut.setTextSize(24);
    clearBut.setAvailable(true);
    sideBarBack.loadImage("images/sidebar.jpg");
    string font=config->prop;
    for (unsigned int i=0; i<config->size(); i++) {
        xmlParse xml=config->child[i];
        if (xml.label=="instrument") {
            string col=xml.prop;
            string title=xml.name;
            cout << title << " current instrument" << endl;
            long color=strtol(col.c_str(),NULL,0);
            int curInst=instruments.size();
            unsigned char note, channel;
            bool repeat=false;
            double delay=0;
            map<string,int> list;
            list["note"]=0;
            list["channel"]=1;
            list["repeat"]=2;
            list["delay"]=3;
            list["dropdown"]=4;
            cout << xml.size() << " number of children" << endl;
            for(int j=0; j<xml.size(); j++) {
                string * node=xml.getSubnode(j);
                switch (list.find(node[0])->second) {
                case 0:
                    note=ofToInt(node[1]);
                    break;
                case 1:
                    channel=ofToInt(node[1]);
                    break;
                case 2:
                    repeat=true;
                    break;
                case 3:
                    delay=ofToFloat(node[1]);
                    break;
                case 8:
                    //ddGroup.push_back(ofDropDown(&xml->child[i]));
                    break;
                default:
                    break;
                }
            }
            instruments.push_back( instrument(title,channel,note,repeat));
            instruments[curInst].setColor(color);
            instruments[curInst].setDelay(delay);
        }
    }
    setHeight();
}
Exemplo n.º 16
0
void Part::write(XmlWriter& xml) const
      {
      xml.stag("Part");
      foreach(const Staff* staff, _staves)
            staff->write(xml);
      if (!_show)
            xml.tag("show", _show);
      xml.tag("trackName", _partName);
      instrument()->write(xml, const_cast<Part*>(this)); // Safe, we do not write anything to it
      xml.etag();
      }
Exemplo n.º 17
0
void Part::read(XmlReader& e)
      {
      while (e.readNextStartElement()) {
            if (readProperties(e))
                 ;
            else
                  e.unknown();
            }
      if (_partName.isEmpty())
            _partName = instrument()->trackName();
      }
Exemplo n.º 18
0
void Part::write(Xml& xml) const
      {
      xml.stag("Part");
      foreach(const Staff* staff, _staves)
            staff->write(xml);
      if (!_show)
            xml.tag("show", _show);
      xml.tag("trackName", _partName);
      instrument()->write(xml);
      xml.etag();
      }
Exemplo n.º 19
0
void CffPlayer::rewind(const boost::optional<size_t>& subsong)
{
    ModPlayer::rewind(subsong);

    // default instruments
    for(int i = 0; i < 9; i++)
    {
        channel(i).instrument = i;

        const ModPlayer::Instrument& inst = instrument(i);
        channel(i).carrierVolume = 0x3f - (inst.data[10] & 0x3f);
        channel(i).modulatorVolume = 0x3f - (inst.data[9] & 0x3f);
    }
}
Exemplo n.º 20
0
/***********************************************************************//**
 * @brief Print LAT observation information
 *
 * @param[in] chatter Chattiness (defaults to NORMAL).
 * @return String containing LAT observation information.
 ***************************************************************************/
std::string GLATObservation::print(const GChatter& chatter) const
{
    // Initialise result string
    std::string result;

    // Continue only if chatter is not silent
    if (chatter != SILENT) {

        // Append header
        result.append("=== GLATObservation ===");

        // Append information
        result.append("\n"+gammalib::parformat("Name")+name());
        result.append("\n"+gammalib::parformat("Identifier")+id());
        result.append("\n"+gammalib::parformat("Instrument")+instrument());
        result.append("\n"+gammalib::parformat("Statistics")+statistics());
        result.append("\n"+gammalib::parformat("Ontime")+gammalib::str(ontime()));
        result.append("\n"+gammalib::parformat("Livetime")+gammalib::str(livetime()));

        // Append response
        result.append("\n"+m_response.print(gammalib::reduce(chatter)));

        // Append livetime cube
        if (m_ltcube != NULL) {
            result.append("\n"+m_ltcube->print(gammalib::reduce(chatter)));
        }
        else {
            result.append("\n"+gammalib::parformat("LAT livetime cube")+"undefined");
        }

        // EXPLICIT: Append events
        if (chatter >= EXPLICIT) {
            if (m_events != NULL) {
                result.append("\n"+m_events->print(gammalib::reduce(chatter)));
            }
        }

    } // endif: chatter was not silent

    // Return result
    return result;
}
Exemplo n.º 21
0
QVariant Part::getProperty(P_ID id) const
      {
      switch (id) {
            case P_ID::VISIBLE:
                  return QVariant(_show);
            case P_ID::USE_DRUMSET:
                  return instrument()->useDrumset();
            case P_ID::PART_VOLUME:
                  return volume();
            case P_ID::PART_MUTE:
                  return mute();
            case P_ID::PART_PAN:
                  return pan();
            case P_ID::PART_REVERB:
                  return reverb();
            case P_ID::PART_CHORUS:
                  return chorus();
            default:
                  return QVariant();
            }
      }
void	InstrumentTest::testSave() {
	debug(LOG_DEBUG, DEBUG_LOG, 0, "testSave() begin");
	ConfigurationPtr	config = Configuration::get(dbfilename);
	Database	database = config->database();
	DeviceMapperConfigurationPtr	devicemapperconfig
		= DeviceMapperConfiguration::get(config);

	// make sure we have an entry in the device mapper for TEST
	DeviceMapperPtr	devicemapper = devicemapperconfig->devicemapper();
	DeviceMap	mapentry(DeviceName("filterwheel:sx/0"));
	mapentry.name("TEST");
	mapentry.unitid(1291);
	mapentry.description("test filterwheel");
	devicemapper->add(mapentry);

	// create an instrument
	InstrumentPtr	instrument(new Instrument(database, "BLUBB"));

	// add a few components
	InstrumentComponentPtr	camera = InstrumentComponentPtr(
		new InstrumentComponentDirect(DeviceName::Camera,
			DeviceName("camera:simulator/camera"), 7, "localhost"));
	instrument->add(camera);
	InstrumentComponentPtr	ccd = InstrumentComponentPtr(
		new InstrumentComponentDerived(DeviceName::Ccd,
			*instrument, DeviceName::Camera, 5));
	instrument->add(ccd);
	InstrumentComponentPtr	filterwheel = InstrumentComponentPtr(
		new InstrumentComponentMapped(DeviceName::Filterwheel,
			database, "TEST"));
	instrument->add(filterwheel);

	// add the instrument to the database
	InstrumentConfigurationPtr	instrumentconfig
		= InstrumentConfiguration::get(config);
	instrumentconfig->addInstrument(instrument);

	debug(LOG_DEBUG, DEBUG_LOG, 0, "testSave() end");
}
Exemplo n.º 23
0
/* Initialise the solving machinery with Assassin Circe
 * @param si identifies root slice of stipulation
 * @param interval_start start of the slices interval to be initialised
 */
void circe_assassin_initialise_solving(slice_index si,
                                       slice_type interval_start)
{
  TraceFunctionEntry(__func__);
  TraceFunctionParam("%u",si);
  TraceEnumerator(slice_type,interval_start,"");
  TraceFunctionParamListEnd();

  circe_insert_rebirth_avoider(si,
                               interval_start,
                               STCirceDeterminedRebirth,
                               alloc_fork_slice(STCirceTestRebirthSquareEmpty,no_slice),
                               STCirceRebirthOnNonEmptySquare,
                               STCircePlacingReborn);
  circe_instrument_solving(si,
                           interval_start,
                           STCirceRebirthOnNonEmptySquare,
                           alloc_pipe(STCirceAssassinAssassinate));

  instrument(si);

  TraceFunctionExit(__func__);
  TraceFunctionResultEnd();
}
Exemplo n.º 24
0
Arquivo: conf.cpp Projeto: Adamiko/los
static void readConfigMidiPort(Xml& xml)/*{{{*/
{
    int idx = 0;
    qint64 id = -1;
    QString device;
    bool isGlobal = false;

    QString instrument("GM");

    QList<PatchSequence*> patchSequences;
    QList<QPair<int, QString> > presets;

    int openFlags = 1;
    int dic = 0;
    int doc = 0;
    int type = MidiDevice::ALSA_MIDI;
    bool cachenrpn = false;

    MidiDevice* dev = 0;

    for (;;)
    {
        Xml::Token token = xml.parse();
        if (token == Xml::Error || token == Xml::End)
            break;
        QString tag = xml.s1();
        switch (token)
        {
            case Xml::TagStart:
                if (tag == "name")
                {
                    device = xml.parse1();
                    if (!dev)//Look for it as an alsa or already created device
                        dev = midiDevices.find(device);
                }
                else if (tag == "type")
                {
                    type = xml.parseInt();
                }
                else if (tag == "record")
                {   // old
                    bool f = xml.parseInt();
                    if (f)
                        openFlags |= 2;
                }
                else if (tag == "openFlags")
                    openFlags = xml.parseInt();
                else if (tag == "defaultInChans")
                    dic = xml.parseInt();
                else if (tag == "defaultOutChans")
                    doc = xml.parseInt();
                else if (tag == "instrument")
                {
                    instrument = xml.parse1();
                }
                else if (tag == "channel")
                {
                    readPortChannel(xml, idx);
                }
                else if (tag == "preset" || tag == "patchSequence")
                {
                    PatchSequence* p = readMidiPortPatchSequences(xml);
                    if (p)
                        patchSequences.append(p);
                }
                else if(tag == "midiPreset")
                {
                    presets.append(readMidiPortPreset(xml));
                }
                else if(tag == "cacheNRPN")
                {
                    cachenrpn = xml.parseInt();
                }
                else
                    xml.skip(tag);
                break;
            case Xml::Attribut:
                if (tag == "idx")
                {//Check to see if this port is already used, and bump if so
                    idx = xml.s2().toInt();
                    int freePort = getFreeMidiPort();
                    if(freePort != idx)
                    {//Set a flag here so we know when loading tracks later that we are dealing with an old file or global inputs changed
                        idx = freePort;
                    }
                }
                else if(tag == "portId")
                {//New style
                    id = xml.s2().toLongLong();
                    idx = getFreeMidiPort();
                }
                else if(tag == "isGlobalInput")
                {//Find the matching input if posible and set our index to it
                    isGlobal = xml.s2().toInt();
                }
                break;
            case Xml::TagEnd:
                if (tag == "midiport")
                {
                    if(isGlobal)
                    {//Find the global input that matches
                        //
                        if(gInputListPorts.size())
                        {
                            int myport = -1;
                            for(int i = 0; i < gInputListPorts.size(); ++i)
                            {
                                myport =  gInputListPorts.at(i);

                                MidiPort* inport = &midiPorts[i];
                                if(inport && inport->device() && inport->device()->name() == device)
                                {
                                    idx = myport;
                                    break;
                                }
                            }
                        }
                    }

                    if (idx < 0 || idx >= MIDI_PORTS)
                    {
                        fprintf(stderr, "bad midi port %d (>%d)\n",
                                idx, MIDI_PORTS);
                        idx = 0;
                    }

                    if (!dev)
                    {
                        if (type == MidiDevice::JACK_MIDI)
                        {
                            dev = MidiJackDevice::createJackMidiDevice(device); // p3.3.55

                            if (debugMsg)
                                fprintf(stderr, "readConfigMidiPort: creating jack midi device %s\n", device.toLatin1().constData());
                        }
                        else
                            dev = midiDevices.find(device);
                    }

                    if (debugMsg && !dev)
                        fprintf(stderr, "readConfigMidiPort: device not found %s\n", device.toLatin1().constData());

                    MidiPort* mp = &midiPorts[idx];
                    if(id)
                        mp->setPortId(id);

                    mp->setInstrument(registerMidiInstrument(instrument));
                    mp->setDefaultInChannels(dic);
                    mp->setDefaultOutChannels(doc);

                    //Indicate the port was found in the song file, even if no device is assigned to it.
                    mp->setFoundInSongFile(true);

                    if (!patchSequences.isEmpty())
                    {
                        for (int i = 0; i < patchSequences.size(); ++i)
                        {
                            mp->appendPatchSequence(patchSequences.at(i));
                        }
                    }
                    if(!presets.isEmpty())
                    {
                        for(int i = 0; i < presets.size(); ++i)
                        {
                            QPair<int, QString> pair = presets.at(i);
                            mp->addPreset(pair.first, pair.second);
                        }
                    }

                    if (dev)
                    {
                        dev->setOpenFlags(openFlags);
                        midiSeq->msgSetMidiDevice(mp, dev);
                        dev->setCacheNRPN(cachenrpn);
                    }
                    losMidiPorts.insert(mp->id(), mp);
                    return;
                }
            default:
                break;
        }
    }
}/*}}}*/
Exemplo n.º 25
0
/** Execute the algorithm.
 */
void LoadNXSPE::exec() {
  std::string filename = getProperty("Filename");
  // quicly check if it's really nxspe
  try {
    ::NeXus::File file(filename);
    std::string mainEntry = (*(file.getEntries().begin())).first;
    file.openGroup(mainEntry, "NXentry");
    file.openData("definition");
    if (identiferConfidence(file.getStrData()) < 1) {
      throw std::invalid_argument("Not NXSPE");
    }
    file.close();
  } catch (...) {
    throw std::invalid_argument("Not NeXus or not NXSPE");
  }

  // Load the data
  ::NeXus::File file(filename);

  std::string mainEntry = (*(file.getEntries().begin())).first;
  file.openGroup(mainEntry, "NXentry");

  file.openGroup("NXSPE_info", "NXcollection");
  std::map<std::string, std::string> entries = file.getEntries();
  std::vector<double> temporary;
  double fixed_energy, psi = 0.;

  if (!entries.count("fixed_energy")) {
    throw std::invalid_argument("fixed_energy field was not found");
  }
  file.openData("fixed_energy");
  file.getData(temporary);
  fixed_energy = temporary.at(0);
  file.closeData();

  if (entries.count("psi")) {
    file.openData("psi");
    file.getData(temporary);
    psi = temporary.at(0);
    file.closeData();
  }

  int kikfscaling = 0;
  if (entries.count("ki_over_kf_scaling")) {
    file.openData("ki_over_kf_scaling");
    std::vector<int> temporaryint;
    file.getData(temporaryint);
    kikfscaling = temporaryint.at(0);
    file.closeData();
  }

  file.closeGroup(); // NXSPE_Info

  file.openGroup("data", "NXdata");
  entries = file.getEntries();

  if (!entries.count("data")) {
    throw std::invalid_argument("data field was not found");
  }
  file.openData("data");
  ::NeXus::Info info = file.getInfo();
  std::size_t numSpectra = static_cast<std::size_t>(info.dims.at(0));
  std::size_t numBins = static_cast<std::size_t>(info.dims.at(1));
  std::vector<double> data;
  file.getData(data);
  file.closeData();

  if (!entries.count("error")) {
    throw std::invalid_argument("error field was not found");
  }
  file.openData("error");
  std::vector<double> error;
  file.getData(error);
  file.closeData();

  if (!entries.count("energy")) {
    throw std::invalid_argument("energy field was not found");
  }
  file.openData("energy");
  std::vector<double> energies;
  file.getData(energies);
  file.closeData();

  if (!entries.count("azimuthal")) {
    throw std::invalid_argument("azimuthal field was not found");
  }
  file.openData("azimuthal");
  std::vector<double> azimuthal;
  file.getData(azimuthal);
  file.closeData();

  if (!entries.count("azimuthal_width")) {
    throw std::invalid_argument("azimuthal_width field was not found");
  }
  file.openData("azimuthal_width");
  std::vector<double> azimuthal_width;
  file.getData(azimuthal_width);
  file.closeData();

  if (!entries.count("polar")) {
    throw std::invalid_argument("polar field was not found");
  }
  file.openData("polar");
  std::vector<double> polar;
  file.getData(polar);
  file.closeData();

  if (!entries.count("polar_width")) {
    throw std::invalid_argument("polar_width field was not found");
  }
  file.openData("polar_width");
  std::vector<double> polar_width;
  file.getData(polar_width);
  file.closeData();

  // distance might not have been saved in all NXSPE files
  std::vector<double> distance;
  if (entries.count("distance")) {
    file.openData("distance");
    file.getData(distance);
    file.closeData();
  }

  file.closeGroup(); // data group
  file.closeGroup(); // Main entry
  file.close();

  // check if dimensions of the vectors are correct
  if ((error.size() != data.size()) || (azimuthal.size() != numSpectra) ||
      (azimuthal_width.size() != numSpectra) || (polar.size() != numSpectra) ||
      (polar_width.size() != numSpectra) ||
      ((energies.size() != numBins) && (energies.size() != numBins + 1))) {
    throw std::invalid_argument(
        "incompatible sizes of fields in the NXSPE file");
  }

  MatrixWorkspace_sptr outputWS = boost::dynamic_pointer_cast<MatrixWorkspace>(
      WorkspaceFactory::Instance().create("Workspace2D", numSpectra,
                                          energies.size(), numBins));
  // Need to get hold of the parameter map
  outputWS->getAxis(0)->unit() = UnitFactory::Instance().create("DeltaE");
  outputWS->setYUnit("SpectraNumber");

  // add logs
  outputWS->mutableRun().addLogData(
      new PropertyWithValue<double>("Ei", fixed_energy));
  outputWS->mutableRun().addLogData(new PropertyWithValue<double>("psi", psi));
  outputWS->mutableRun().addLogData(new PropertyWithValue<std::string>(
      "ki_over_kf_scaling", kikfscaling == 1 ? "true" : "false"));

  // Set Goniometer
  Geometry::Goniometer gm;
  gm.pushAxis("psi", 0, 1, 0, psi);
  outputWS->mutableRun().setGoniometer(gm, true);

  // generate instrument
  Geometry::Instrument_sptr instrument(new Geometry::Instrument("NXSPE"));
  outputWS->setInstrument(instrument);

  Geometry::ObjComponent *source = new Geometry::ObjComponent("source");
  source->setPos(0.0, 0.0, -10.0);
  instrument->add(source);
  instrument->markAsSource(source);
  Geometry::ObjComponent *sample = new Geometry::ObjComponent("sample");
  instrument->add(sample);
  instrument->markAsSamplePos(sample);

  Geometry::Object_const_sptr cuboid(
      createCuboid(0.1, 0.1, 0.1)); // FIXME: memory hog on rendering. Also,
                                    // make each detector separate size
  for (std::size_t i = 0; i < numSpectra; ++i) {
    double r = 1.0;
    if (!distance.empty()) {
      r = distance.at(i);
    }

    Kernel::V3D pos;
    pos.spherical(r, polar.at(i), azimuthal.at(i));

    Geometry::Detector *det =
        new Geometry::Detector("pixel", static_cast<int>(i + 1), sample);
    det->setPos(pos);
    det->setShape(cuboid);
    instrument->add(det);
    instrument->markAsDetector(det);
  }

  Geometry::ParameterMap &pmap = outputWS->instrumentParameters();
  std::vector<double>::iterator itdata = data.begin(), iterror = error.begin(),
                                itdataend, iterrorend;
  API::Progress prog = API::Progress(this, 0.0, 0.9, numSpectra);
  for (std::size_t i = 0; i < numSpectra; ++i) {
    itdataend = itdata + numBins;
    iterrorend = iterror + numBins;
    outputWS->dataX(i) = energies;
    if ((!boost::math::isfinite(*itdata)) || (*itdata <= -1e10)) // masked bin
    {
      outputWS->dataY(i) = std::vector<double>(numBins, 0);
      outputWS->dataE(i) = std::vector<double>(numBins, 0);
      pmap.addBool(outputWS->getDetector(i)->getComponentID(), "masked", true);
    } else {
      outputWS->dataY(i) = std::vector<double>(itdata, itdataend);
      outputWS->dataE(i) = std::vector<double>(iterror, iterrorend);
    }
    itdata = (itdataend);
    iterror = (iterrorend);
    prog.report();
  }

  setProperty("OutputWorkspace", outputWS);
}
Exemplo n.º 26
0
void Part::setLongName(const QString& s)
      {
      instrument()->setLongName(s);
      }
Exemplo n.º 27
0
/** Executes the algorithm. Reading in the file and creating and populating
 *  the output workspace
 *
 *  @throw FileError Thrown if unable to parse XML file
 */
void LoadInstrumentFromNexus::exec()
{
  // Retrieve the filename from the properties
  m_filename = getPropertyValue("Filename");

  // Get the input workspace
  const MatrixWorkspace_sptr localWorkspace = getProperty("Workspace");

  // open Nexus file
  MuonNexusReader nxload;
  if (nxload.readFromFile(m_filename.c_str()) != 0)
  {
    g_log.error("Unable to open file " + m_filename);
    throw Exception::FileError("Unable to open File:" , m_filename);
  }
  progress(0.5);
  // Create a new Instrument with the right name and add it to the workspace
  Geometry::Instrument_sptr instrument(new Geometry::Instrument(nxload.getInstrumentName()));
  localWorkspace->setInstrument(instrument);

  // Add dummy source and samplepos to instrument
  // The L2 and 2-theta values from nexus file assumed to be relative to sample position

  Geometry::ObjComponent *samplepos = new Geometry::ObjComponent("Unknown",instrument.get());
  instrument->add(samplepos);
  instrument->markAsSamplePos(samplepos);
  samplepos->setPos(0.0,0.0,0.0);

  Geometry::ObjComponent *source = new Geometry::ObjComponent("Unknown",instrument.get());
  instrument->add(source);
  instrument->markAsSource(source);
  double l1;
  // If user has provided an L1, use that
  if ( ! Kernel::ConfigService::Instance().getValue("instrument.L1", l1) )
  {
    // Otherwise try and get it from the nexus file - but not there at present!
    // l1 = nxload.ivpb.i_l1;
    // Default to 10 if the file doesn't have it set
    if (l1 == 0)  l1 = 10.0;
  }
  source->setPos(0.0,-1.0*l1,0.0);
    progress(1.0);

  // add detectors
  /* **** Ignoring all this for the moment - the sample Nexus files do not contain most of these values

  const int numDetector = nxload.i_det;    // number of detectors
  const int* const detID = nxload.udet;    // detector IDs
  const float* const r = nxload.len2;      // distance from sample
  const float* const angle = nxload.tthe;  // angle between indicent beam and direction from sample to detector (two-theta)

  for (int i = 0; i < numDetector; ++i)
  {
    // Create a new detector. Instrument will take ownership of pointer so no need to delete.
    Geometry::Detector *detector = new Geometry::Detector("det",samplepos);
    Kernel::V3D pos;
    pos.spherical(r[i], angle[i], 0.0);
    detector->setPos(pos);

    // set detector ID, add copy to instrument and mark it
    detector->setID(detID[i]);
    instrument->add(detector);
    instrument->markAsDetector(detector);
  }

  // Now mark the up the monitors
  const int numMonitors = nxload.i_mon;     // The number of monitors
  const int* const monIndex = nxload.mdet;  // Index into the udet array for each monitor
  for (int j = 0; j < numMonitors; ++j)
  {
    const int detectorToMark = detID[monIndex[j]-1];
    Geometry::Detector *det = dynamic_cast<Geometry::Detector*>(instrument->getDetector(detectorToMark));
    det->markAsMonitor();
    g_log.information() << "Detector with ID " << detectorToMark << " marked as a monitor." << std::endl;
  }

  // Information to the user about what info is extracted from nexus file
  g_log.information() << "SamplePos component added with position set to (0,0,0).\n"
    << "Detector components added with position coordinates assumed to be relative to the position of the sample; \n"
    << "L2 and two-theta values were read from nexus file and used to set the r and theta spherical coordinates; \n"
    << "the remaining spherical coordinate phi was set to zero.\n"
    << "Source component added with position set to (0,-" << l1 << ",0). In standard configuration, with \n"
    << "the beam along y-axis pointing from source to sample, this implies the source is " << l1 << "m in front \n"
    << "of the sample. This value can be changed via the 'instrument.l1' configuration property.\n";
  */

  return;
}
void InstrumentTrack::processInEvent( const MidiEvent& event, const MidiTime& time, f_cnt_t offset )
{
	bool eventHandled = false;

	switch( event.type() )
	{
		// we don't send MidiNoteOn, MidiNoteOff and MidiKeyPressure
		// events to instrument as NotePlayHandle will send them on its
		// own
		case MidiNoteOn:
			if( event.velocity() > 0 )
			{
				NotePlayHandle* nph;
				m_notesMutex.lock();
				if( m_notes[event.key()] == NULL )
				{
					nph = NotePlayHandleManager::acquire( this, offset,
								typeInfo<f_cnt_t>::max() / 2,
								Note( MidiTime(), MidiTime(), event.key(), event.volume( midiPort()->baseVelocity() ) ),
								NULL, event.channel(),
								NotePlayHandle::OriginMidiInput );
					m_notes[event.key()] = nph;
					if( ! Engine::mixer()->addPlayHandle( nph ) )
					{
						m_notes[event.key()] = NULL;
					}
				}
				m_notesMutex.unlock();
				eventHandled = true;
				break;
			}

		case MidiNoteOff:
			m_notesMutex.lock();
			if( m_notes[event.key()] != NULL )
			{
				// do actual note off and remove internal reference to NotePlayHandle (which itself will
				// be deleted later automatically)
				m_notes[event.key()]->noteOff( offset );
				m_notes[event.key()] = NULL;
			}
			m_notesMutex.unlock();
			eventHandled = true;
			break;

		case MidiKeyPressure:
			if( m_notes[event.key()] != NULL )
			{
				// setVolume() calls processOutEvent() with MidiKeyPressure so the
				// attached instrument will receive the event as well
				m_notes[event.key()]->setVolume( event.volume( midiPort()->baseVelocity() ) );
			}
			eventHandled = true;
			break;

		case MidiPitchBend:
			// updatePitch() is connected to m_pitchModel::dataChanged() which will send out
			// MidiPitchBend events
			m_pitchModel.setValue( m_pitchModel.minValue() + event.pitchBend() * m_pitchModel.range() / MidiMaxPitchBend );
			break;

		case MidiControlChange:
			if( event.controllerNumber() == MidiControllerSustain )
			{
				if( event.controllerValue() > MidiMaxControllerValue/2 )
				{
					m_sustainPedalPressed = true;
				}
				else
				{
					m_sustainPedalPressed = false;
				}
			}
			if( event.controllerNumber() == MidiControllerAllSoundOff ||
				event.controllerNumber() == MidiControllerAllNotesOff ||
				event.controllerNumber() == MidiControllerOmniOn ||
				event.controllerNumber() == MidiControllerOmniOff ||
				event.controllerNumber() == MidiControllerMonoOn ||
				event.controllerNumber() == MidiControllerPolyOn )
			{
				silenceAllNotes();
			}
			break;

		case MidiMetaEvent:
			// handle special cases such as note panning
			switch( event.metaEvent() )
			{
				case MidiNotePanning:
					if( m_notes[event.key()] != NULL )
					{
						eventHandled = true;
						m_notes[event.key()]->setPanning( event.panning() );
					}
					break;
				default:
					qWarning( "InstrumentTrack: unhandled MIDI meta event: %i", event.metaEvent() );
					break;
			}
			break;

		default:
			break;
	}

	if( eventHandled == false && instrument()->handleMidiEvent( event, time, offset ) == false )
	{
		qWarning( "InstrumentTrack: unhandled MIDI event %d", event.type() );
	}

}
Exemplo n.º 29
0
void Part::setShortName(const QString& s)
      {
      instrument()->setShortName(s);
      }
Exemplo n.º 30
0
/** Execute the algorithm. Currently just calls SaveISISNexusProcessed but could
 *  call write other formats if support added
 *
 *  @throw runtime_error Thrown if algorithm cannot execute
 */
void SaveISISNexus::exec() {
  // Retrieve the filename from the properties
  inputFilename = getPropertyValue("InputFileName");

  m_isisRaw = new ISISRAW2;
  rawFile = fopen(inputFilename.c_str(), "rb");
  if (rawFile == nullptr) {
    throw Exception::FileError("Cannot open file ", inputFilename);
  }
  m_isisRaw->ioRAW(rawFile, true);

  nper = m_isisRaw->t_nper; // number of periods
  nsp = m_isisRaw->t_nsp1;  // number of spectra
  ntc = m_isisRaw->t_ntc1;  // number of time channels
  nmon = m_isisRaw->i_mon;  // number of monitors
  ndet = m_isisRaw->i_det;  // number of detectors

  std::string outputFilename = getPropertyValue("OutputFileName");

  NXstatus status;
  float flt;

  status = NXopen(outputFilename.c_str(), NXACC_CREATE5, &handle);
  if (status != NX_OK) {
    throw std::runtime_error("Cannot open file " + outputFilename +
                             " for writing.");
  }
  NXmakegroup(handle, "raw_data_1", "NXentry");
  NXopengroup(handle, "raw_data_1", "NXentry");
  write_isis_vms_compat();
  saveString("beamline", " ");

  flt = static_cast<float>(m_isisRaw->rpb.r_dur); // could be wrong
  saveFloatOpen("collection_time", &flt, 1);
  putAttr("units", "second");
  close();

  saveStringOpen("definition", "TOFRAW");
  putAttr("version", "1.0");
  putAttr("url",
          "http://definition.nexusformat.org/instruments/TOFRAW/?version=1.0");
  close();

  saveStringOpen("definition_local", "ISISTOFRAW");
  putAttr("version", "1.0");
  putAttr("url",
          "http://svn.isis.rl.ac.uk/instruments/ISISTOFRAW/?version=1.0");
  close();

  flt = static_cast<float>(m_isisRaw->rpb.r_dur);
  saveFloatOpen("duration", &flt, 1);
  putAttr("units", "second");
  close();

  start_time_str.assign(m_isisRaw->hdr.hd_date, m_isisRaw->hdr.hd_date + 12);
  toISO8601(start_time_str);
  start_time_str += 'T';
  start_time_str +=
      std::string(m_isisRaw->hdr.hd_time, m_isisRaw->hdr.hd_time + 8);
  saveCharOpen("start_time", &start_time_str[0], 19);
  putAttr("units", "ISO8601");
  close();

  std::string str;
  str.assign(m_isisRaw->rpb.r_enddate, m_isisRaw->rpb.r_enddate + 12);
  toISO8601(str);
  str += 'T';
  str += std::string(m_isisRaw->rpb.r_endtime, m_isisRaw->rpb.r_endtime + 8);
  saveCharOpen("end_time", &str[0], 19);
  putAttr("units", "ISO8601");
  close();

  saveChar("title", m_isisRaw->r_title, 80);
  saveInt("good_frames", &m_isisRaw->rpb.r_goodfrm);

  std::string experiment_identifier = std::to_string(m_isisRaw->rpb.r_prop);
  saveChar("experiment_identifier", &experiment_identifier[0],
           static_cast<int>(experiment_identifier.size()));
  int tmp_int(0);
  saveInt("measurement_first_run", &tmp_int);
  saveString("measurement_id", " ");
  saveString("measurement_label", " ");
  saveString("measurement_subid", " ");
  saveString("measurement_type", " ");

  saveCharOpen("name", &m_isisRaw->i_inst, 8);
  putAttr("short_name", m_isisRaw->hdr.inst_abrv, 3);
  close();

  logNotes();

  saveString("program_name", "isisicp");

  saveFloatOpen("proton_charge", &m_isisRaw->rpb.r_gd_prtn_chrg, 1);
  putAttr("units", "uamp.hour");
  close();

  saveFloatOpen("proton_charge_raw", &m_isisRaw->rpb.r_tot_prtn_chrg, 1);
  putAttr("units", "uamp.hour");
  close();

  saveInt("raw_frames", &m_isisRaw->rpb.r_rawfrm);

  run_cycle();

  saveInt("run_number", &m_isisRaw->r_number);

  // script_name
  // seci_config

  instrument();

  make_detector_1_link();

  write_monitors();

  user();

  sample();

  runlog();

  selog();

  NXclosegroup(handle); // raw_data_1
  status = NXclose(&handle);

  delete m_isisRaw;
}