예제 #1
0
 /** @return the value of the StartTime property */
 Mantid::Kernel::DateAndTime LiveDataAlgorithm::getStartTime() const
 {
   std::string date = getPropertyValue("StartTime");
   if (date.empty())
     return DateAndTime();
   return DateAndTime(date);
 }
예제 #2
0
bool RecreateCmpFile( BOARD * aBrd, const wxString& aFullCmpFileName )
{
    FILE* cmpFile;

    cmpFile = wxFopen( aFullCmpFileName, wxT( "wt" ) );

    if( cmpFile == NULL )
        return false;

    fprintf( cmpFile, "Cmp-Mod V01 Created by PcbNew   date = %s\n", TO_UTF8( DateAndTime() ) );

    MODULE* module = aBrd->m_Modules;
    for( ; module != NULL; module = module->Next() )
    {
        fprintf( cmpFile, "\nBeginCmp\n" );
        fprintf( cmpFile, "TimeStamp = %8.8lX\n", (unsigned long)module->GetTimeStamp() );
        fprintf( cmpFile, "Path = %s\n", TO_UTF8( module->GetPath() ) );
        fprintf( cmpFile, "Reference = %s;\n",
                 !module->GetReference().IsEmpty() ?
                 TO_UTF8( module->GetReference() ) : "[NoRef]" );
        fprintf( cmpFile, "ValeurCmp = %s;\n",
                 !module->GetValue().IsEmpty() ?
                 TO_UTF8( module->GetValue() ) : "[NoVal]" );
        fprintf( cmpFile, "IdModule  = %s;\n", module->GetFPID().Format().c_str() );
        fprintf( cmpFile, "EndCmp\n" );
    }

    fprintf( cmpFile, "\nEndListe\n" );
    fclose( cmpFile );

    return true;
}
예제 #3
0
int WinEDA_ModuleEditFrame::Create_Librairie(const wxString & LibName)
/**********************************************************************/
{
FILE * lib_module;
wxString msg;
	
	if ( wxFileExists(LibName) )
		{
		msg = _("Library exists ") + LibName;
		DisplayError(this, msg);
		return(0);
		}

	if ((lib_module = wxFopen(LibName, wxT("wt") ))  == NULL )
		{
		msg = _("Unable to create ") + LibName;
		DisplayError(this, msg);
		return(-1);
		}

	/* Ecriture de l'entete de la nouvelle librairie */
	if( fprintf(lib_module,ENTETE_LIBRAIRIE) == 0)
		{
		msg = _("Create error ") + LibName;
		DisplayError(this, msg);
		fclose(lib_module) ; return(-1);
		}

	fprintf(lib_module,"  %s\n", DateAndTime(cbuf));
	fputs("$INDEX\n",lib_module);
	fputs("$EndINDEX\n",lib_module);
	fclose(lib_module) ;

	return(1);
}
예제 #4
0
void PROJECT::ConfigSave( const SEARCH_STACK& aSList, const wxString& aGroupName,
        const PARAM_CFG_ARRAY& aParams, const wxString& aFileName )
{
    std::unique_ptr<wxConfigBase> cfg( configCreate( aSList, aGroupName, aFileName ) );

    if( !cfg.get() )
    {
        // could not find template
        return;
    }

    cfg->SetPath( wxT( "/" ) );

    cfg->Write( wxT( "update" ), DateAndTime() );

    // @todo: pass in aLastClient wxString:
    cfg->Write( wxT( "last_client" ), Pgm().App().GetAppName() );

    // Save parameters
    cfg->DeleteGroup( aGroupName );     // Erase all data
    cfg->Flush();

    cfg->SetPath( aGroupName );
    cfg->Write( wxT( "version" ), CONFIG_VERSION );

    cfg->SetPath( wxT( "/" ) );

    wxConfigSaveParams( cfg.get(), aParams, aGroupName );

    cfg->SetPath( wxT( "/" ) );

    // cfg is deleted here by std::unique_ptr, that saves the *.pro file to disk
}
예제 #5
0
/**
 * Function start_plot
 * Write GERBER header to file
 * initialize global variable g_Plot_PlotOutputFile
 * @param aFile: an opened file to write to
 */
bool GERBER_PLOTTER::start_plot( FILE* aFile )
{
    wxASSERT( !output_file );
    final_file  = aFile;

    // Create a temporary filename to store gerber file
    // note tmpfile() does not work under Vista and W7 in user mode
    m_workFilename = filename + wxT(".tmp");
    work_file   = wxFopen( m_workFilename, wxT( "wt" ));
    output_file = work_file;
    wxASSERT( output_file );

    if( output_file == NULL )
        return false;

    wxString Title = creator + wxT( " " ) + GetBuildVersion();
    fprintf( output_file, "G04 (created by %s) date %s*\n",
             TO_UTF8( Title ), TO_UTF8( DateAndTime() ) );

    // Specify linear interpol (G01), unit = INCH (G70), abs format (G90):
    fputs( "G01*\nG70*\nG90*\n", output_file );
    fputs( "%MOIN*%\n", output_file );     // set unites = INCHES

    /* Set gerber format to 3.4 */
    fputs( "G04 Gerber Fmt 3.4, Leading zero omitted, Abs format*\n%FSLAX34Y34*%\n",
           output_file );

    fputs( "G04 APERTURE LIST*\n", output_file );
    /* Select the default aperture */
    set_current_line_width( -1 );

    return true;
}
예제 #6
0
/** Read a pulse ID file
 * @param filename :: file to load.
 * @param throwError :: Flag to trigger error throwing instead of just logging
 */
void LoadEventPreNexus::readPulseidFile(const std::string &filename,
                                        const bool throwError) {
  this->proton_charge_tot = 0.;
  this->num_pulses = 0;

  // jump out early if there isn't a filename
  if (filename.empty()) {
    this->g_log.information("NOT using a pulseid file");
    return;
  }

  std::vector<Pulse> *pulses;

  // set up for reading
  // Open the file; will throw if there is any problem
  try {
    BinaryFile<Pulse> pulseFile(filename);

    // Get the # of pulse
    this->num_pulses = pulseFile.getNumElements();
    this->g_log.information() << "Using pulseid file \"" << filename
                              << "\", with " << num_pulses << " pulses.\n";

    // Load all the data
    pulses = pulseFile.loadAll();
  } catch (runtime_error &e) {
    if (throwError) {
      throw;
    } else {
      this->g_log.information()
          << "Encountered error in pulseidfile (ignoring file): " << e.what()
          << "\n";
      return;
    }
  }

  double temp;

  if (num_pulses > 0) {
    this->pulsetimes.reserve(num_pulses);
    for (size_t i = 0; i < num_pulses; i++) {
      Pulse &it = (*pulses)[i];
      this->pulsetimes.push_back(
          DateAndTime((int64_t)it.seconds, (int64_t)it.nanoseconds));
      this->event_indices.push_back(it.event_index);

      temp = it.pCurrent;
      this->proton_charge.push_back(temp);
      if (temp < 0.)
        this->g_log.warning("Individual proton charge < 0 being ignored");
      else
        this->proton_charge_tot += temp;
    }
  }

  this->proton_charge_tot = this->proton_charge_tot * CURRENT_CONVERSION;

  // Clear the vector
  delete pulses;
}
예제 #7
0
void WinEDA_ModuleEditFrame::Export_Module(MODULE* ptmod, bool createlib)
/************************************************************************/
/*
Genere 1 fichier type Empreinte a partir de la description du module sur PCB
*/
{
wxString FullFileName, Mask( wxT("*") );
char Line[1025];
FILE * dest;
wxString msg, path;

	if ( ptmod == NULL ) return;

	ptmod->m_LibRef = ptmod->m_Reference->m_Text;
	FullFileName = ptmod->m_LibRef;
	FullFileName += createlib ? LibExtBuffer : EXT_CMP;

	Mask += createlib ? LibExtBuffer : EXT_CMP;

	if ( createlib ) path = g_RealLibDirBuffer; 
	FullFileName = EDA_FileSelector( createlib ? _("Create lib") : _("Export Module:"),
					path,				/* Chemin par defaut */
					FullFileName,		/* nom fichier par defaut */
					createlib ? LibExtBuffer : EXT_CMP,			/* extension par defaut */
					Mask,		/* Masque d'affichage */
					this,
					wxSAVE,
					TRUE
					);

	if ( FullFileName.IsEmpty() ) return;

	if ( createlib  && wxFileExists(FullFileName) )
	{
		msg.Printf( _("File %s exists, OK to replace ?"),
				FullFileName.GetData());
		if( ! IsOK(this, msg) ) return;
	}

	/* Generation du fichier Empreinte */
	if ( (dest = wxFopen(FullFileName, wxT("wt")) ) == NULL )
	{
		msg.Printf( _("Unable to create <%s>"),FullFileName.GetData()) ;
		DisplayError(this, msg) ;
		return ;
	}

	fprintf(dest,"%s  %s\n", ENTETE_LIBRAIRIE, DateAndTime(Line));
	fputs("$INDEX\n",dest);

	fprintf(dest,"%s\n", CONV_TO_UTF8(ptmod->m_LibRef) );
	fputs("$EndINDEX\n",dest);

	m_Pcb->m_Modules->WriteDescr(dest);

	fputs("$EndLIBRARY\n",dest);
	fclose(dest) ;
	msg.Printf( _("Module exported in file <%s>"),FullFileName.GetData()) ;
	DisplayInfo(this, msg) ;
}
예제 #8
0
static void WriteNetListPspice(wxWindow * frame, FILE *f,
		 bool use_netnames)
/*************************************************************/
/* Routine de generation du fichier netliste ( Format PSPICE )
	si use_netnames = TRUE
		les nodes sont identifies par le netname
	sinon	les nodes sont identifies par le netnumber

	tous les textes graphiques commençant par [.-+]pspice ou  [.-+]gnucap
	sont considérés comme des commandes a placer dans la netliste
		[.-]pspice ou gnucap sont en debut
		+pspice et +gnucap sont en fin de netliste
*/
{
char Line[1024];
BASE_SCREEN *CurrScreen;
EDA_BaseStruct *DrawList;
EDA_SchComponentStruct *Component;
int ii, nbitems;
wxString text;
wxArrayString SpiceCommandAtBeginFile, SpiceCommandAtEndFile;
wxString msg;
#define BUFYPOS_LEN 4
wxChar bufnum[BUFYPOS_LEN+1];

	DateAndTime(Line);
	fprintf( f, "* %s (Spice format) creation date: %s\n\n", NETLIST_HEAD_STRING, Line );

	/* Create text list starting by [.-]pspice , or [.-]gnucap (simulator commands) */
	/* and create text list starting by [+]pspice , or [+]gnucap (simulator commands) */
	bufnum[BUFYPOS_LEN] = 0;
	for(CurrScreen = ScreenSch; CurrScreen != NULL; CurrScreen = (BASE_SCREEN*)CurrScreen->Pnext )
	{
		for ( DrawList = CurrScreen->EEDrawList; DrawList != NULL; DrawList = DrawList->Pnext )
		{
			wxChar ident;
			if ( DrawList->m_StructType != DRAW_TEXT_STRUCT_TYPE ) continue;
			#define DRAWTEXT ((DrawTextStruct *) DrawList)
			text = DRAWTEXT->m_Text; if ( text.IsEmpty() ) continue;
			ident = text.GetChar(0);
			if ( ident != '.' && ident != '-' && ident != '+' ) continue;
			text.Remove(0,1);	//Remove the first char.
			text.Remove(6);		//text contains 6 char.
			if( ( text == wxT("pspice") ) || ( text == wxT("gnucap") ) )
			{
				/* Put the Y position as an ascii string, for sort by vertical position,
				using usual sort string by alphabetic value */
				int ypos = DRAWTEXT->m_Pos.y;
				for ( ii = 0; ii < BUFYPOS_LEN; ii++ )
				{
					bufnum[BUFYPOS_LEN-1-ii] = (ypos & 63) + ' '; ypos >>= 6;
				}
				text = DRAWTEXT->m_Text.AfterFirst( ' ');
				msg.Printf( wxT("%s %s"),bufnum, text.GetData());	// First BUFYPOS_LEN char are the Y position
				if ( ident == '+' ) SpiceCommandAtEndFile.Add(msg);
				else SpiceCommandAtBeginFile.Add(msg);
			}
		}
	}
예제 #9
0
파일: erc.cpp 프로젝트: OpenEE/micad
bool WriteDiagnosticERC( const wxString& aFullFileName )
{
    wxString    msg;

    wxFFile file( aFullFileName, wxT( "wt" ) );

    if( !file.IsOpened() )
        return false;

    msg = _( "ERC report" );
    msg << wxT(" (") << DateAndTime() << wxT( ", " )
        << _( "Encoding UTF8" ) << wxT( " )\n" );

    int err_count = 0;
    int warn_count = 0;
    int total_count = 0;
    SCH_SHEET_LIST sheetList;
    SCH_SHEET_PATH* sheet;

    for( sheet = sheetList.GetFirst(); sheet != NULL; sheet = sheetList.GetNext() )
    {
        msg << wxString::Format( _( "\n***** Sheet %s\n" ),
                                 GetChars( sheet->PathHumanReadable() ) );

        for( SCH_ITEM* item = sheet->LastDrawList(); item != NULL; item = item->Next() )
        {
            if( item->Type() != SCH_MARKER_T )
                continue;

            SCH_MARKER* marker = (SCH_MARKER*) item;

            if( marker->GetMarkerType() != MARKER_BASE::MARKER_ERC )
                continue;

            total_count++;

            if( marker->GetErrorLevel() == MARKER_BASE::MARKER_SEVERITY_ERROR )
                err_count++;

            if( marker->GetErrorLevel() == MARKER_BASE::MARKER_SEVERITY_WARNING )
                warn_count++;

            msg << marker->GetReporter().ShowReport();
        }
    }

    msg << wxString::Format( _( "\n ** ERC messages: %d  Errors %d  Warnings %d\n" ),
                             total_count, err_count, warn_count );

    // Currently: write report unsing UTF8 (as usual in Kicad).
    // TODO: see if we can use the current encoding page (mainly for Windows users),
    // Or other format (HTML?)
    file.Write( msg );

    // wxFFile dtor will close the file.

    return true;
}
bool GERBER_PLOTTER::StartPlot()
{
    wxASSERT( outputFile );

    finalFile = outputFile;     // the actual gerber file will be created later

    // Create a temporary filename to store gerber file
    // note tmpfile() does not work under Vista and W7 in user mode
    m_workFilename = filename + wxT(".tmp");
    workFile   = wxFopen( m_workFilename, wxT( "wt" ));
    outputFile = workFile;
    wxASSERT( outputFile );

    if( outputFile == NULL )
        return false;

    for( unsigned ii = 0; ii < m_headerExtraLines.GetCount(); ii++ )
    {
        if( ! m_headerExtraLines[ii].IsEmpty() )
            fprintf( outputFile, "%s\n", TO_UTF8( m_headerExtraLines[ii] ) );
    }

    // Set coordinate format to 3.6 or 4.5 absolute, leading zero omitted
    // the number of digits for the integer part of coordintes is needed
    // in gerber format, but is not very important when omitting leading zeros
    // It is fixed here to 3 (inch) or 4 (mm), but is not actually used
    int leadingDigitCount = m_gerberUnitInch ? 3 : 4;

    fprintf( outputFile, "%%FSLAX%d%dY%d%d*%%\n",
             leadingDigitCount, m_gerberUnitFmt,
             leadingDigitCount, m_gerberUnitFmt );
    fprintf( outputFile,
             "G04 Gerber Fmt %d.%d, Leading zero omitted, Abs format (unit %s)*\n",
             leadingDigitCount, m_gerberUnitFmt,
             m_gerberUnitInch ? "inch" : "mm" );

    wxString Title = creator + wxT( " " ) + GetBuildVersion();
    fprintf( outputFile, "G04 Created by KiCad (%s) date %s*\n",
             TO_UTF8( Title ), TO_UTF8( DateAndTime() ) );

    /* Mass parameter: unit = INCHES/MM */
    if( m_gerberUnitInch )
        fputs( "%MOIN*%\n", outputFile );
    else
        fputs( "%MOMM*%\n", outputFile );

    // Be sure the usual dark polarity is selected:
    fputs( "%LPD*%\n", outputFile );

    // Specify linear interpol (G01):
    fputs( "G01*\n", outputFile );

    fputs( "G04 APERTURE LIST*\n", outputFile );

    return true;
}
예제 #11
0
파일: LogManager.cpp 프로젝트: dezed/mantid
/** Return the run end time as given by the 'end_time' or 'run_end' property.
 *  'end_time' is tried first, falling back to 'run_end' if the former isn't
 * found.
 *  @returns The end time of the run
 *  @throws std::runtime_error if neither property is defined
 */
const Kernel::DateAndTime LogManager::endTime() const {
  const std::string end_prop("end_time");
  if (hasProperty(end_prop)) {
    try {
      return DateAndTime(getProperty(end_prop)->value());
    } catch (std::invalid_argument &) { /*Swallow and move on*/
    }
  }

  const std::string run_end_prop("run_end");
  if (hasProperty(run_end_prop)) {
    try {
      return DateAndTime(getProperty(run_end_prop)->value());
    } catch (std::invalid_argument &) { /*Swallow and move on*/
    }
  }

  throw std::runtime_error("No valid end time has been set for this run.");
}
예제 #12
0
void EDA_APP::WriteProjectConfig( const wxString&  fileName,
                                  const wxString&  GroupName,
                                  PARAM_CFG_BASE** List )
{
    PARAM_CFG_BASE* pt_cfg;
    wxString        msg;

    ReCreatePrjConfig( fileName, GroupName, FORCE_LOCAL_CONFIG );

    /* Write time (especially to avoid bug wxFileConfig that writes the
     * wrong item if declaration [xx] in first line (If empty group)
     */
    m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR );

    msg = DateAndTime();
    m_projectSettings->Write( wxT( "update" ), msg );

    msg = GetAppName();
    m_projectSettings->Write( wxT( "last_client" ), msg );

    /* Save parameters */
    m_projectSettings->DeleteGroup( GroupName );   // Erase all data
    m_projectSettings->Flush();

    m_projectSettings->SetPath( GroupName );
    m_projectSettings->Write( wxT( "version" ), CONFIG_VERSION );
    m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR );

    for( ; List != NULL && *List != NULL; List++ )
    {
        pt_cfg = *List;

        if( pt_cfg->m_Group )
            m_projectSettings->SetPath( pt_cfg->m_Group );
        else
            m_projectSettings->SetPath( GroupName );

        if( pt_cfg->m_Setup )
            continue;

        if ( pt_cfg->m_Type == PARAM_COMMAND_ERASE )    // Erase all data
        {
            if( pt_cfg->m_Ident )
                m_projectSettings->DeleteGroup( pt_cfg->m_Ident );
        }
        else
        {
            pt_cfg->SaveParam( m_projectSettings );
        }
    }

    m_projectSettings->SetPath( UNIX_STRING_DIR_SEP );
    delete m_projectSettings;
    m_projectSettings = NULL;
}
예제 #13
0
static bool WriteDiagnosticERC(const wxString & FullFileName)
/*********************************************************/
/* Genere le fichier des diagnostics
*/
{
    SCH_SCREEN * Window;
    EDA_BaseStruct * DrawStruct;
    DrawMarkerStruct * Marker;
    char Line[256];
    static FILE * OutErc;
    DrawSheetStruct * Sheet;
    wxString msg;

    if( (OutErc = wxFopen( FullFileName, wxT("wt"))) == NULL ) return FALSE;

    DateAndTime(Line);
    msg = _("ERC control");
    fprintf( OutErc, "%s (%s)\n", CONV_TO_UTF8(msg), Line);

    for( Window = ScreenSch; Window != NULL; Window = (SCH_SCREEN*)Window->Pnext )
    {
        Sheet = (DrawSheetStruct *) Window->m_Parent;

        msg.Printf( _("\n***** Sheet %d (%s)\n"),
                    Window->m_SheetNumber,
                    Sheet ? Sheet->m_Field[VALUE].m_Text.GetData() : _("Root"));
        fprintf( OutErc, "%s", CONV_TO_UTF8(msg));

        DrawStruct = Window->EEDrawList;
        for ( ; DrawStruct != NULL; DrawStruct = DrawStruct->Pnext)
        {
            if(DrawStruct->m_StructType != DRAW_MARKER_STRUCT_TYPE )
                continue;
            /* Marqueur trouve */

            Marker = (DrawMarkerStruct * ) DrawStruct;
            if( Marker->m_Type != MARQ_ERC ) continue;
            /* Write diag marqueur */
            msg.Printf( _("ERC: %s (X= %2.3f inches, Y= %2.3f inches\n"),
                        Marker->GetComment().GetData(),
                        (float)Marker->m_Pos.x / 1000,
                        (float)Marker->m_Pos.y / 1000);
            fprintf( OutErc, "%s", CONV_TO_UTF8(msg));
        }
    }
    msg.Printf( _("\n >> Errors ERC: %d\n"), g_EESchemaVar.NbErrorErc);
    fprintf( OutErc, "%s", CONV_TO_UTF8(msg));
    fclose ( OutErc );

    return TRUE;
}
예제 #14
0
파일: erc.cpp 프로젝트: natsfr/kicad
bool WriteDiagnosticERC( const wxString& aFullFileName )
{
    SCH_ITEM*       item;
    SCH_MARKER*     marker;
    static FILE*    file;
    SCH_SHEET_PATH* sheet;
    wxString        msg;
    int             count = 0;

    if( ( file = wxFopen( aFullFileName, wxT( "wt" ) ) ) == NULL )
        return false;

    msg = _( "ERC report" );

    fprintf( file, "%s (%s)\n", TO_UTF8( msg ), TO_UTF8( DateAndTime() ) );

    SCH_SHEET_LIST sheetList;

    for( sheet = sheetList.GetFirst(); sheet != NULL; sheet = sheetList.GetNext() )
    {
        msg.Printf( _( "\n***** Sheet %s\n" ), GetChars( sheet->PathHumanReadable() ) );

        fprintf( file, "%s", TO_UTF8( msg ) );

        for( item = sheet->LastDrawList(); item != NULL; item = item->Next() )
        {
            if( item->Type() != SCH_MARKER_T )
                continue;

            marker = (SCH_MARKER*) item;

            if( marker->GetMarkerType() != MARK_ERC )
                continue;

            if( marker->GetMarkerType() == ERR )
                count++;

            msg = marker->GetReporter().ShowReport();
            fprintf( file, "%s", TO_UTF8( msg ) );
        }
    }

    msg.Printf( _( "\n >> Errors ERC: %d\n" ), count );
    fprintf( file, "%s", TO_UTF8( msg ) );
    fclose( file );

    return true;
}
예제 #15
0
void EDA_APP::WriteProjectConfig( const wxString&  fileName,
                                  const wxString&  GroupName,
                                  const PARAM_CFG_ARRAY& params )
{
    ReCreatePrjConfig( fileName, GroupName, FORCE_LOCAL_CONFIG );

    /* Write date ( surtout pour eviter bug de wxFileConfig
     * qui se trompe de rubrique si declaration [xx] en premiere ligne
     * (en fait si groupe vide) */
    m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR );

    m_projectSettings->Write( wxT( "update" ), DateAndTime() );
    m_projectSettings->Write( wxT( "last_client" ), GetAppName() );

    /* Save parameters */
    m_projectSettings->DeleteGroup( GroupName );   // Erase all data
    m_projectSettings->Flush();

    m_projectSettings->SetPath( GroupName );
    m_projectSettings->Write( wxT( "version" ), CONFIG_VERSION );
    m_projectSettings->SetPath( wxCONFIG_PATH_SEPARATOR );

    BOOST_FOREACH( const PARAM_CFG_BASE& param, params )
    {
        if( param.m_Group )
            m_projectSettings->SetPath( param.m_Group );
        else
            m_projectSettings->SetPath( GroupName );

        if( param.m_Setup )
            continue;

        if ( param.m_Type == PARAM_COMMAND_ERASE )    // Erase all data
        {
            if( param.m_Ident )
                m_projectSettings->DeleteGroup( param.m_Ident );
        }
        else
        {
            param.SaveParam( m_projectSettings );
        }
    }

    m_projectSettings->SetPath( UNIX_STRING_DIR_SEP );
    delete m_projectSettings;
    m_projectSettings = NULL;
}
예제 #16
0
/*
 * CreatePartsAndLabelsFullList()
 * Main function to create the list of components and/or labels
 * (global labels, hierarchical labels and pin sheets )
 */
void DIALOG_BUILD_BOM::CreatePartsAndLabelsFullList( bool aIncludeSubComponents )
{
    FILE*    f;
    wxString msg;

    if( ( f = wxFopen( m_listFileName, wxT( "wt" ) ) ) == NULL )
    {
        msg = _( "Failed to open file " );
        msg << m_listFileName;
        DisplayError( this, msg );
        return;
    }

    BOM_LISTER bom_lister;
    bom_lister.SetIncludeSubCmp( aIncludeSubComponents );
    bom_lister.SetCvsFormOff();
    bom_lister.SetPrintLocation( s_Add_Location );
    // Set the list of fields to add to list
    for( int ii = FOOTPRINT; ii < FIELD8; ii++ )
        if( IsFieldChecked( ii ) )
            bom_lister.AddFieldIdToPrintList( ii );

    // creates the list file
    wxString Title = wxGetApp().GetAppName() + wxT( " " ) + GetBuildVersion();

    fprintf( f, "%s  >> Creation date: %s\n", TO_UTF8( Title ), TO_UTF8( DateAndTime() ) );

    if( m_ListCmpbyRefItems->GetValue() )
        bom_lister.PrintComponentsListByReferenceHumanReadable( f );

    if( m_ListCmpbyValItems->GetValue() )
        bom_lister.PrintComponentsListByValue( f );

    // Create list of global labels, hierachical labels and pins sheets

    if( m_GenListLabelsbySheet->GetValue() )
        bom_lister.PrintGlobalAndHierarchicalLabelsList( f, true );

    if( m_GenListLabelsbyVal->GetValue() )
        bom_lister.PrintGlobalAndHierarchicalLabelsList( f, false );

    msg = _( "\n#End List\n" );
    fprintf( f, "%s", TO_UTF8( msg ) );
    fclose( f );
}
void GBR_TO_PCB_EXPORTER::writePcbHeader()
{
    fprintf( m_fp, "PCBNEW-BOARD Version 1 date %s\n\n# Created by GerbView %s\n\n",
             TO_UTF8( DateAndTime() ), TO_UTF8( GetBuildVersion() ) );
    fprintf( m_fp, "$GENERAL\n" );
    fprintf( m_fp, "encoding utf-8\n" );
    fprintf( m_fp, "Units deci-mils\n" );

    // Write copper layer count
    fprintf( m_fp, "LayerCount %d\n", m_pcbCopperLayersCount );
    // Write enabled layer mask:
    int lmask = ALL_NO_CU_LAYERS | EXTERNAL_CU_LAYERS;

    for( int ii = 0; ii < m_pcbCopperLayersCount - 2; ii++ )
        lmask |= 2 << ii;

    fprintf( m_fp, "EnabledLayers %08X\n", lmask );
    fprintf( m_fp, "$EndGENERAL\n\n" );

    // Creates void setup
    fprintf( m_fp, "$SETUP\n" );
    fprintf( m_fp, "$EndSETUP\n\n" );
}
예제 #18
0
/** Return the minimum time possible */
DateAndTime DateAndTime::minimum()
{
  return DateAndTime(MIN_NANOSECONDS);
}
bool NETLIST_EXPORTER_CADSTAR::Write( const wxString& aOutFileName, unsigned aNetlistOptions )
{
    (void)aNetlistOptions;      //unused
    int ret = 0;
    FILE* f = NULL;

    if( ( f = wxFopen( aOutFileName, wxT( "wt" ) ) ) == NULL )
    {
        wxString msg;
        msg.Printf( _( "Failed to create file '%s'" ),
                    GetChars( aOutFileName ) );
        DisplayError( NULL, msg );
        return false;
    }

    wxString StartCmpDesc = StartLine + wxT( "ADD_COM" );
    wxString msg;
    wxString footprint;
    SCH_SHEET_PATH* sheet;
    EDA_ITEM* DrawList;
    SCH_COMPONENT* component;
    wxString title = wxT( "Eeschema " ) + GetBuildVersion();

    ret |= fprintf( f, "%sHEA\n", TO_UTF8( StartLine ) );
    ret |= fprintf( f, "%sTIM %s\n", TO_UTF8( StartLine ), TO_UTF8( DateAndTime() ) );
    ret |= fprintf( f, "%sAPP ", TO_UTF8( StartLine ) );
    ret |= fprintf( f, "\"%s\"\n", TO_UTF8( title ) );
    ret |= fprintf( f, "\n" );

    // Prepare list of nets generation
    for( unsigned ii = 0; ii < m_masterList->size(); ii++ )
        m_masterList->GetItem( ii )->m_Flag = 0;

    // Create netlist module section
    m_ReferencesAlreadyFound.Clear();

    SCH_SHEET_LIST SheetList;

    for( sheet = SheetList.GetFirst(); sheet != NULL; sheet = SheetList.GetNext() )
    {
        for( DrawList = sheet->LastDrawList(); DrawList != NULL; DrawList = DrawList->Next() )
        {
            DrawList = component = findNextComponentAndCreatePinList( DrawList, sheet );

            if( component == NULL )
                break;

            /*
            doing nothing with footprint
            if( !component->GetField( FOOTPRINT )->IsVoid() )
            {
                footprint = component->GetField( FOOTPRINT )->m_Text;
                footprint.Replace( wxT( " " ), wxT( "_" ) );
            }
            else
                footprint = wxT( "$noname" );
            */

            msg = component->GetRef( sheet );
            ret |= fprintf( f, "%s     ", TO_UTF8( StartCmpDesc ) );
            ret |= fprintf( f, "%s", TO_UTF8( msg ) );

            msg = component->GetField( VALUE )->GetText();
            msg.Replace( wxT( " " ), wxT( "_" ) );
            ret |= fprintf( f, "     \"%s\"", TO_UTF8( msg ) );
            ret |= fprintf( f, "\n" );
        }
    }

    ret |= fprintf( f, "\n" );

    m_SortedComponentPinList.clear();

    if( ! writeListOfNets( f ) )
        ret = -1;   // set error

    ret |= fprintf( f, "\n%sEND\n", TO_UTF8( StartLine ) );

    fclose( f );

    return ret >= 0;
}
예제 #20
0
void LIB_EDIT_FRAME::SaveOneSymbol()
{
    wxString        msg;
    PROJECT&        prj = Prj();
    SEARCH_STACK*   search = prj.SchSearchS();
    LIB_PART*       part = GetCurPart();

    if( !part || part->GetDrawItemList().empty() )
        return;

    wxString default_path = prj.GetRString( PROJECT::SCH_LIB_PATH );
    if( !default_path )
        default_path = search->LastVisitedPath();

    wxFileDialog dlg( this, _( "Export Symbol Drawings" ), default_path,
                      part->GetName(), SchematicSymbolFileWildcard,
                      wxFD_SAVE | wxFD_OVERWRITE_PROMPT );

    if( dlg.ShowModal() == wxID_CANCEL )
        return;

    wxFileName fn = dlg.GetPath();

    /* The GTK file chooser doesn't return the file extension added to
     * file name so add it here. */
    if( fn.GetExt().IsEmpty() )
        fn.SetExt( SchematicSymbolFileExtension );

    prj.SetRString( PROJECT::SCH_LIB_PATH, fn.GetPath() );

    msg.Printf( _( "Saving symbol in '%s'" ), GetChars( fn.GetPath() ) );
    SetStatusText( msg );

    wxString line;

    // File header
    line << wxT( LIBFILE_IDENT ) << wxT( " " ) << LIB_VERSION_MAJOR
         << wxT( "." ) << LIB_VERSION_MINOR << wxT( "  SYMBOL  " )
         << wxT( "Date: " ) << DateAndTime() << wxT( "\n" );

    // Component name comment and definition.
    line << wxT( "# SYMBOL " ) << part->GetName() << wxT( "\n#\nDEF " )
         << part->GetName() << wxT( " " );

    if( !part->GetReferenceField().GetText().IsEmpty() )
        line << part->GetReferenceField().GetText() << wxT( " " );
    else
        line << wxT( "~ " );

    line << 0 << wxT( " " ) << part->GetPinNameOffset() << wxT( " " );

    if( part->ShowPinNumbers() )
        line << wxT( "Y " );
    else
        line << wxT( "N " );

    if( part->ShowPinNames() )
        line << wxT( "Y " );
    else
        line << wxT( "N " );

    line << wxT( "1 0 N\n" );

    try
    {
        FILE_OUTPUTFORMATTER    formatter( fn.GetFullPath() );

        try
        {
            formatter.Print( 0, "%s", TO_UTF8( line ) );
            part->GetReferenceField().Save( formatter );
            part->GetValueField().Save( formatter );
            formatter.Print( 0, "DRAW\n" );

            LIB_ITEMS& drawList = part->GetDrawItemList();

            for( LIB_ITEM& item : drawList )
            {
                if( item.Type() == LIB_FIELD_T )
                    continue;

                // Don't save unused parts or alternate body styles.
                if( m_unit && item.GetUnit() && ( item.GetUnit() != m_unit ) )
                    continue;

                if( m_convert && item.GetConvert() && ( item.GetConvert() != m_convert ) )
                    continue;

                item.Save( formatter );
            }

            formatter.Print( 0, "ENDDRAW\n" );
            formatter.Print( 0, "ENDDEF\n" );
        }
        catch( const IO_ERROR& ioe )
        {
            msg.Printf( _( "An error occurred attempting to save symbol file '%s'" ),
                        GetChars( fn.GetFullPath() ) );
            DisplayError( this, msg );
        }
    }
    catch( const IO_ERROR& ioe )
    {
        DisplayError( this, ioe.errorText );
        return;
    }
}
예제 #21
0
bool LibArchive(wxWindow * frame, const wxString & ArchFullFileName)
/*******************************************************************/
/*
Creation du fichier librairie contenant tous les composants utilisés dans
le projet en cours
retourne  TRUE si fichier créé
*/
{
wxString DocFileName, msg;
char Line[256];
FILE *ArchiveFile, *DocFile;
EDA_BaseStruct ** ListStruct;
EDA_LibComponentStruct ** ListEntry, *Entry;
int ii, NbItems;
char * Text;


	/* Creation de la liste des elements */
	NbItems = GenListeCmp(NULL );	// Comptage des composants
	if ( NbItems == 0 ) return FALSE;

	ListStruct = (EDA_BaseStruct **)
			MyZMalloc( NbItems * sizeof(EDA_BaseStruct **) );
	if (ListStruct == NULL ) return FALSE;

	/* Calcul de la liste des composants */
	GenListeCmp(ListStruct);

	/* Calcul de la liste des Entrees de librairie
		et Remplacement des alias par les composants "Root" */
	ListEntry = (EDA_LibComponentStruct ** )
				MyZMalloc( NbItems * sizeof(EDA_LibComponentStruct *) );
	if (ListEntry == NULL ) return FALSE;

	for ( ii = 0; ii < NbItems; ii++ )
	{
		Text = ( (EDA_SchComponentStruct*)ListStruct[ii])->m_ChipName;
		Entry = FindLibPart(Text, "", FIND_ROOT);
		ListEntry[ii] = Entry;	// = NULL si Composant non trouvé en librairie
	}

	MyFree(ListStruct);

	qsort( ListEntry, NbItems, sizeof(EDA_LibComponentStruct *),
			(int(*)(const void*, const void*))TriListEntry);

	/* mise a jour extension fichier doc associe */
	DocFileName = ArchFullFileName;
	ChangeFileNameExt(DocFileName, ".bck");

	if ((ArchiveFile = fopen(ArchFullFileName.GetData(), "wt")) == NULL)
	{
		MyFree(ListEntry);
		msg = _("Failed to create archive lib file ") + ArchFullFileName;
		DisplayError(frame, msg);
		return FALSE;
	}

	if ((DocFile = fopen(DocFileName.GetData(), "wt")) == NULL)
	{
		msg = _("Failed to create doc lib file ") + DocFileName;
		DisplayError(frame, msg);
	}

	fprintf(ArchiveFile,"%s  %s\n#\n", LIBFILE_IDENT,DateAndTime(Line));
	if( DocFile)
		fprintf(DocFile,"%s  %s\n", DOCFILE_IDENT, DateAndTime(Line));

	/* Generation des elements */
	for ( ii = 0; ii < NbItems; ii++ )
	{
		if ( ListEntry[ii] == NULL )	// Composant non trouvé en librairie
		{
		continue;
			}
		if ( ii == 0 )
		{
			WriteOneLibEntry(frame, ArchiveFile, ListEntry[ii]);
			if( DocFile ) WriteOneDocLibEntry(DocFile, ListEntry[ii]);
		}
		else if ( ListEntry[ii-1] != ListEntry[ii] )
		{
			 WriteOneLibEntry(frame, ArchiveFile, ListEntry[ii]);
			 if( DocFile ) WriteOneDocLibEntry(DocFile, ListEntry[ii]);
		}
	}

	/* Generation fin de fichier */
	fprintf(ArchiveFile,"#\n#EndLibrary\n");
	fclose(ArchiveFile);

	if( DocFile )
	{
		fprintf(DocFile,"#\n#End Doc Library\n");
		fclose(DocFile);
	}

	MyFree(ListEntry);

	return TRUE;
}
/**
 * Determine the instrument from the various input parameters.
 *
 * @return The correct instrument.
 */
Instrument_const_sptr CreateChunkingFromInstrument::getInstrument() {
  // try the input workspace
  MatrixWorkspace_sptr inWS = getProperty(PARAM_IN_WKSP);
  if (inWS) {
    return inWS->getInstrument();
  }

  // temporary workspace to hang everything else off of
  MatrixWorkspace_sptr tempWS(new Workspace2D());
  // name of the instrument
  string instName = getPropertyValue(PARAM_INST_NAME);

  // see if there is an input file
  string filename = getPropertyValue(PARAM_IN_FILE);
  if (!filename.empty()) {
    string top_entry_name("entry"); // TODO make more flexible

    // get the instrument name from the filename
    size_t n = filename.rfind('/');
    if (n != std::string::npos) {
      std::string temp = filename.substr(n + 1, filename.size() - n - 1);
      n = temp.find('_');
      if (n != std::string::npos && n > 0) {
        instName = temp.substr(0, n);
      }
    }

    // read information from the nexus file itself
    try {
      NeXus::File nxsfile(filename);

      // get the run start time
      string start_time;
      nxsfile.openGroup(top_entry_name, "NXentry");
      nxsfile.readData("start_time", start_time);
      tempWS->mutableRun().addProperty(
          "run_start", DateAndTime(start_time).toISO8601String(), true);

      // get the instrument name
      nxsfile.openGroup("instrument", "NXinstrument");
      nxsfile.readData("name", instName);
      nxsfile.closeGroup();

      // Test if IDF exists in file, move on quickly if not
      nxsfile.openPath("instrument/instrument_xml");
      nxsfile.close();
      IAlgorithm_sptr loadInst =
          createChildAlgorithm("LoadIDFFromNexus", 0.0, 0.2);
      // Now execute the Child Algorithm. Catch and log any error, but don't
      // stop.
      try {
        loadInst->setPropertyValue("Filename", filename);
        loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", tempWS);
        loadInst->setPropertyValue("InstrumentParentPath", top_entry_name);
        loadInst->execute();
      } catch (std::invalid_argument &) {
        g_log.error("Invalid argument to LoadIDFFromNexus Child Algorithm ");
      } catch (std::runtime_error &) {
        g_log.debug("No instrument definition found in " + filename + " at " +
                    top_entry_name + "/instrument");
      }

      if (loadInst->isExecuted())
        return tempWS->getInstrument();
      else
        g_log.information("No IDF loaded from Nexus file.");

    } catch (::NeXus::Exception &) {
      g_log.information("No instrument definition found in " + filename +
                        " at " + top_entry_name + "/instrument");
    }
  }

  // run LoadInstrument if other methods have not run
  string instFilename = getPropertyValue(PARAM_INST_FILE);

  Algorithm_sptr childAlg = createChildAlgorithm("LoadInstrument", 0.0, 0.2);
  childAlg->setProperty<MatrixWorkspace_sptr>("Workspace", tempWS);
  childAlg->setPropertyValue("Filename", instFilename);
  childAlg->setPropertyValue("InstrumentName", instName);
  childAlg->executeAsChildAlg();
  return tempWS->getInstrument();
}
XNODE* NETLIST_EXPORTER_GENERIC::makeDesignHeader()
{
    SCH_SCREEN* screen;
    XNODE*     xdesign = node( wxT( "design" ) );
    XNODE*     xtitleBlock;
    XNODE*     xsheet;
    XNODE*     xcomment;
    wxString   sheetTxt;
    wxFileName sourceFileName;

    // the root sheet is a special sheet, call it source
    xdesign->AddChild( node( wxT( "source" ), g_RootSheet->GetScreen()->GetFileName() ) );

    xdesign->AddChild( node( wxT( "date" ), DateAndTime() ) );

    // which Eeschema tool
    xdesign->AddChild( node( wxT( "tool" ), wxT( "Eeschema " ) + GetBuildVersion() ) );

    /*
        Export the sheets information
    */
    SCH_SHEET_LIST sheetList( g_RootSheet );

    for( unsigned i = 0;  i < sheetList.size();  i++ )
    {
        screen = sheetList[i].LastScreen();

        xdesign->AddChild( xsheet = node( wxT( "sheet" ) ) );

        // get the string representation of the sheet index number.
        // Note that sheet->GetIndex() is zero index base and we need to increment the
        // number by one to make it human readable
        sheetTxt.Printf( wxT( "%u" ), i + 1 );
        xsheet->AddAttribute( wxT( "number" ), sheetTxt );
        xsheet->AddAttribute( wxT( "name" ), sheetList[i].PathHumanReadable() );
        xsheet->AddAttribute( wxT( "tstamps" ), sheetList[i].Path() );


        TITLE_BLOCK tb = screen->GetTitleBlock();

        xsheet->AddChild( xtitleBlock = node( wxT( "title_block" ) ) );

        xtitleBlock->AddChild( node( wxT( "title" ), tb.GetTitle() ) );
        xtitleBlock->AddChild( node( wxT( "company" ), tb.GetCompany() ) );
        xtitleBlock->AddChild( node( wxT( "rev" ), tb.GetRevision() ) );
        xtitleBlock->AddChild( node( wxT( "date" ), tb.GetDate() ) );

        // We are going to remove the fileName directories.
        sourceFileName = wxFileName( screen->GetFileName() );
        xtitleBlock->AddChild( node( wxT( "source" ), sourceFileName.GetFullName() ) );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("1") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment1() );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("2") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment2() );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("3") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment3() );

        xtitleBlock->AddChild( xcomment = node( wxT( "comment" ) ) );
        xcomment->AddAttribute( wxT("number"), wxT("4") );
        xcomment->AddAttribute( wxT( "value" ), tb.GetComment4() );
    }

    return xdesign;
}
예제 #24
0
/** Return the maximum time possible */
DateAndTime DateAndTime::maximum()
{
  return DateAndTime(MAX_NANOSECONDS);
}
예제 #25
0
/** Executes the algorithm
 */
void FilterByTime::exec()
{
  EventWorkspace_const_sptr inputWS = this->getProperty("InputWorkspace");

  // ---- Find the start/end times ----
  DateAndTime start, stop;

  double start_dbl, stop_dbl;
  start_dbl = getProperty("StartTime");
  stop_dbl = getProperty("StopTime");

  std::string start_str, stop_str;
  start_str = getPropertyValue("AbsoluteStartTime");
  stop_str = getPropertyValue("AbsoluteStopTime");

  if ( (start_str != "") && (stop_str != "") && (start_dbl <= 0.0) && (stop_dbl <= 0.0) )
  {
    // Use the absolute string
    start = DateAndTime( start_str );
    stop  = DateAndTime( stop_str );
  }
  else if ( (start_str == "") && (stop_str == "") && ((start_dbl > 0.0) || (stop_dbl > 0.0)) )
  {
    // Use the relative times in seconds.
    DateAndTime first = inputWS->getFirstPulseTime();
    DateAndTime last = inputWS->getLastPulseTime();
    start = first + start_dbl;
    if (stop_dbl > 0.0)
    {
      stop = first + stop_dbl;
    }
    else
    {
      this->getLogger().debug() << "No end filter time specified - assuming last pulse" << std::endl;
      stop = last + 10000.0;   // so we get all events - needs to be past last pulse
    }
  }
  else
  {
    //Either both or none were specified
    throw std::invalid_argument("You need to specify either the StartTime or StopTime parameters; or both the AbsoluteStartTime and AbsoluteStopTime parameters; but not other combinations.");
  }

  if (stop <= start)
    throw std::invalid_argument("The stop time should be larger than the start time.");

  // Make a brand new EventWorkspace
  EventWorkspace_sptr outputWS = boost::dynamic_pointer_cast<EventWorkspace>(
        API::WorkspaceFactory::Instance().create("EventWorkspace", inputWS->getNumberHistograms(), 2, 1));
  // Copy geometry over.
  API::WorkspaceFactory::Instance().initializeFromParent(inputWS, outputWS, false);
  // But we don't copy the data.

  setProperty("OutputWorkspace", outputWS);

  size_t numberOfSpectra = inputWS->getNumberHistograms();

  // Initialise the progress reporting object
  Progress prog(this,0.0,1.0,numberOfSpectra);

  // Loop over the histograms (detector spectra)
  PARALLEL_FOR_NO_WSP_CHECK()
  for (int64_t i = 0; i < int64_t(numberOfSpectra); ++i)
  {
    PARALLEL_START_INTERUPT_REGION

    //Get the output event list (should be empty)
    EventList& output_el = outputWS->getEventList(i);
    //and this is the input event list
    const EventList& input_el = inputWS->getEventList(i);

    //Perform the filtering
    input_el.filterByPulseTime(start, stop, output_el);

    prog.report();
    PARALLEL_END_INTERUPT_REGION
  }
  PARALLEL_CHECK_INTERUPT_REGION


  //Now filter out the run, using the DateAndTime type.
  outputWS->mutableRun().filterByTime(start, stop);

}
예제 #26
0
/// A default date and time to use when time is not specified
const DateAndTime DateAndTime::defaultTime()
{
  return DateAndTime("1970-01-01T00:00:00");
}
void EXCELLON_WRITER::WriteEXCELLONHeader()
{
    fputs( "M48\n", m_file );    // The beginning of a header

    if( !m_minimalHeader )
    {
        // The next 2 lines in EXCELLON files are comments:
        wxString msg;
        msg << wxT("KiCad") << wxT( " " ) << GetBuildVersion();

        fprintf( m_file, ";DRILL file {%s} date %s\n", TO_UTF8( msg ),
                 TO_UTF8( DateAndTime() ) );
        msg = wxT( ";FORMAT={" );

        // Print precision:
        if( m_zeroFormat != DECIMAL_FORMAT )
            msg << m_precision.GetPrecisionString();
        else
            msg << wxT( "-:-" );  // in decimal format the precision is irrelevant

        msg << wxT( "/ absolute / " );
        msg << ( m_unitsDecimal ? wxT( "metric" ) :  wxT( "inch" ) );

        /* Adding numbers notation format.
         * this is same as m_Choice_Zeros_Format strings, but NOT translated
         * because some EXCELLON parsers do not like non ASCII values
         * so we use ONLY English (ASCII) strings.
         * if new options are added in m_Choice_Zeros_Format, they must also
         * be added here
         */
        msg << wxT( " / " );

        const wxString zero_fmt[4] =
        {
            wxT( "decimal" ),
            wxT( "suppress leading zeros" ),
            wxT( "suppress trailing zeros" ),
            wxT( "keep zeros" )
        };

        msg << zero_fmt[m_zeroFormat];
        msg << wxT( "}\n" );
        fputs( TO_UTF8( msg ), m_file );
        fputs( "FMAT,2\n", m_file );     // Use Format 2 commands (version used since 1979)
    }

    fputs( m_unitsDecimal ? "METRIC" : "INCH", m_file );

    switch( m_zeroFormat )
    {
    case SUPPRESS_LEADING:
    case DECIMAL_FORMAT:
        fputs( ",TZ\n", m_file );
        break;

    case SUPPRESS_TRAILING:
        fputs( ",LZ\n", m_file );
        break;

    case KEEP_ZEROS:
        fputs( ",TZ\n", m_file ); // TZ is acceptable when all zeros are kept
        break;
    }
}
예제 #28
0
/** - operator to subtract time.
 * @param nanosec :: number of nanoseconds to subtract
 * @return modified DateAndTime.
 */
DateAndTime DateAndTime::operator-(const int64_t nanosec) const
{
  return DateAndTime(_nanoseconds - nanosec);
}
예제 #29
0
/** Load the event_workspace field
 *
 * @param wksp_cls
 * @param progressStart
 * @param progressRange
 * @return
 */
API::MatrixWorkspace_sptr LoadNexusProcessed::loadEventEntry(NXData & wksp_cls, NXDouble & xbins,
    const double& progressStart, const double& progressRange)
{
  NXDataSetTyped<int64_t> indices_data = wksp_cls.openNXDataSet<int64_t>("indices");
  indices_data.load();
  boost::shared_array<int64_t> indices = indices_data.sharedBuffer();
  int numspec = indices_data.dim0()-1;

  int num_xbins = xbins.dim0();
  if (num_xbins < 2) num_xbins = 2;
  EventWorkspace_sptr ws = boost::dynamic_pointer_cast<EventWorkspace>
  (WorkspaceFactory::Instance().create("EventWorkspace", numspec, num_xbins, num_xbins-1));

  // Set the YUnit label
  ws->setYUnit(indices_data.attributes("units"));
  std::string unitLabel = indices_data.attributes("unit_label");
  if (unitLabel.empty()) unitLabel = indices_data.attributes("units");
  ws->setYUnitLabel(unitLabel);

  //Handle optional fields.
  // TODO: Handle inconsistent sizes
  boost::shared_array<int64_t> pulsetimes;
  if (wksp_cls.isValid("pulsetime"))
  {
    NXDataSetTyped<int64_t> pulsetime = wksp_cls.openNXDataSet<int64_t>("pulsetime");
    pulsetime.load();
    pulsetimes = pulsetime.sharedBuffer();
  }

  boost::shared_array<double> tofs;
  if (wksp_cls.isValid("tof"))
  {
    NXDouble tof = wksp_cls.openNXDouble("tof");
    tof.load();
    tofs = tof.sharedBuffer();
  }

  boost::shared_array<float> error_squareds;
  if (wksp_cls.isValid("error_squared"))
  {
    NXFloat error_squared = wksp_cls.openNXFloat("error_squared");
    error_squared.load();
    error_squareds = error_squared.sharedBuffer();
  }

  boost::shared_array<float> weights;
  if (wksp_cls.isValid("weight"))
  {
    NXFloat weight = wksp_cls.openNXFloat("weight");
    weight.load();
    weights = weight.sharedBuffer();
  }

  // What type of event lists?
  EventType type = TOF;
  if (tofs && pulsetimes && weights && error_squareds)
    type = WEIGHTED;
  else if ((tofs && weights && error_squareds))
    type = WEIGHTED_NOTIME;
  else if (pulsetimes && tofs)
    type = TOF;
  else
    throw std::runtime_error("Could not figure out the type of event list!");

  // Create all the event lists
  PARALLEL_FOR_NO_WSP_CHECK()
  for (int wi=0; wi < numspec; wi++)
  {
    PARALLEL_START_INTERUPT_REGION
    int64_t index_start = indices[wi];
    int64_t index_end = indices[wi+1];
    if (index_end >= index_start)
    {
      EventList & el = ws->getEventList(wi);
      el.switchTo(type);

      // Allocate all the required memory
      el.reserve(index_end - index_start);
      el.clearDetectorIDs();

      for (long i=index_start; i<index_end; i++)
      switch (type)
      {
      case TOF:
        el.addEventQuickly( TofEvent( tofs[i], DateAndTime(pulsetimes[i])) );
        break;
      case WEIGHTED:
        el.addEventQuickly( WeightedEvent( tofs[i], DateAndTime(pulsetimes[i]), weights[i], error_squareds[i]) );
        break;
      case WEIGHTED_NOTIME:
        el.addEventQuickly( WeightedEventNoTime( tofs[i], weights[i], error_squareds[i]) );
        break;
      }

      // Set the X axis
      if (this->m_shared_bins)
        el.setX(this->m_xbins);
      else
      {
        MantidVec x;
        x.resize(xbins.dim0());
        for (int i=0; i < xbins.dim0(); i++)
          x[i] = xbins(wi, i);
        el.setX(x);
      }
    }

    progress(progressStart + progressRange*(1.0/numspec));
    PARALLEL_END_INTERUPT_REGION
  }
  PARALLEL_CHECK_INTERUPT_REGION

  // Clean up some stuff
  ws->doneAddingEventLists();

  return ws;
}
예제 #30
0
/** Returns the current DateAndTime, in UTC time, with microsecond precision
 * @return the current time.
 */
DateAndTime DateAndTime::get_current_time()
{
  return DateAndTime(boost::posix_time::microsec_clock::universal_time());
}