Class CSVReader
- java.lang.Object
-
- All Implemented Interfaces:
java.lang.Cloneable
,Actor
,Executable
,FiringsRecordable
,Initializable
,TypedActor
,Changeable
,Debuggable
,DebugListener
,Derivable
,Instantiable
,ModelErrorHandler
,MoMLExportable
,Moveable
,Nameable
public class CSVReader extends LineReader
This actor reads a file or URL, one line at a time, and outputs each line except the first as a record. The first line of the file gives the names of the fields of the output records. The remaining lines give the values of the fields. The output is an ordered record token, which means that the order defined in the first line is preserved.
NOTE: By default, this actor imposes no type constraints on its output. To use it in a model, you must either enable backward type inference (a parameter at the top level of the model), or explicitly declare the output type (by selecting Configure-Ports in the context menu). If you use backward type inference, then the constraints are inferred from how you use the output. For example, if you extract a record field of a particular type, then the output will be constrained to be a record that contains that field. If you declare output types specifically, then every line read from the file must conform. For example, if you set the output the type constraint to "[x = int, y = double]" then the output will be an ordered record where the first field is named "x" and has type int, and the second field is named "y" and has type double. If any line in the file violates this typing, then an exception will be thrown.
If any line has more values than the first line, then the trailing values will be ignored. If any line has fewer values than the first line, then the field values will be an empty string.
By default, the separator between field names and values is a comma, so the file format is the standard CSV (comma-separated value) format. The separator parameter enables changing the separator to tabs or semicolons.
The file or URL is specified using any form acceptable to FileParameter.
Before an end of file is reached, the endOfFile output produces false. In the iteration where the last line of the file is read and produced on the output port, this actor produces true on the endOfFile port. In that iteration, postfire() returns false. If the actor is iterated again, after the end of file, then prefire() and postfire() will both return false, output will produce the string "EOF", and endOfFile will produce true.
In some domains (such as SDF), returning false in postfire() causes the model to cease executing. In other domains (such as DE), this causes the director to avoid further firings of this actor. So usually, the actor will not be invoked again after the end of file is reached.
This actor reads ahead in the file so that it can produce an output true on endOfFile in the same iteration where it outputs the last line. It reads the first two lines in preinitialize(), and subsequently reads a new line in each invocation of postfire(). The data type of the output is also set in preinitialize(), after reading the first line, which defines the structure of the record. line read is produced on the output in the next iteration after it is read.
- Since:
- Ptolemy II 10.0
- Version:
- $Id$
- Author:
- Edward A. Lee
- See Also:
FileParameter
- Pt.AcceptedRating:
- Red (cxh)
- Pt.ProposedRating:
- Yellow (eal)
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class ptolemy.kernel.Entity
Entity.ContainedObjectsIterator
-
-
Field Summary
Fields Modifier and Type Field Description StringParameter
separator
A specification of the separator between items in the table.Parameter
trimSpaces
If true, then trim spaces around each field name and value.-
Fields inherited from class ptolemy.actor.lib.io.LineReader
_currentLine, _firstFiring, _nextLine, _reader, endOfFile, fileOrURL, numberOfLinesToSkip
-
Fields inherited from class ptolemy.actor.lib.Source
_triggered, output, trigger
-
Fields inherited from class ptolemy.actor.TypedAtomicActor
_typesValid
-
Fields inherited from class ptolemy.actor.AtomicActor
_actorFiringListeners, _initializables, _notifyingActorFiring, _stopRequested
-
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _deferChangeRequests, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
-
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
-
-
Constructor Summary
Constructors Constructor Description CSVReader(CompositeEntity container, java.lang.String name)
Construct an actor with the given container and name.
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description protected java.util.Set<Inequality>
_defaultTypeConstraints()
Override the default to eliminate the default type constraints/.void
attributeChanged(Attribute attribute)
If the specified attribute is separator then set a local variable with the value of the separator.void
fire()
Output the data read in the preinitialize() or in the previous invocation of postfire(), if there is any.void
wrapup()
Wrapup execution of this actor.-
Methods inherited from class ptolemy.actor.lib.io.LineReader
_openAndReadFirstTwoLines, clone, initialize, postfire
-
Methods inherited from class ptolemy.actor.lib.Source
_customTypeConstraints, prefire
-
Methods inherited from class ptolemy.actor.TypedAtomicActor
_containedTypeConstraints, _fireAt, _fireAt, attributeTypeChanged, clone, isBackwardTypeInferenceEnabled, newPort, typeConstraintList, typeConstraints
-
Methods inherited from class ptolemy.actor.AtomicActor
_actorFiring, _actorFiring, _declareDelayDependency, addActorFiringListener, addInitializable, connectionsChanged, createReceivers, declareDelayDependency, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, isFireFunctional, isStrict, iterate, newReceiver, outputPortList, preinitialize, pruneDependencies, recordFiring, removeActorFiringListener, removeDependency, removeInitializable, setContainer, stop, stopFire, terminate
-
Methods inherited from class ptolemy.kernel.ComponentEntity
_adjustDeferrals, _checkContainer, _getContainedObject, _propagateExistence, getContainer, instantiate, isAtomic, isOpaque, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, propagateExistence, setName
-
Methods inherited from class ptolemy.kernel.Entity
_addPort, _description, _exportMoMLContents, _removePort, _validateSettables, connectedPortList, connectedPorts, containedObjectsIterator, getAttribute, getPort, getPorts, linkedRelationList, linkedRelations, portList, removeAllPorts, setClassDefinition, uniqueName
-
Methods inherited from class ptolemy.kernel.InstantiableNamedObj
_setParent, exportMoML, getChildren, getElementName, getParent, getPrototypeList, isClassDefinition, isWithinClassDefinition
-
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _containedDecorators, _copyChangeRequestList, _debug, _debug, _debug, _debug, _debug, _executeChangeRequests, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _notifyHierarchyListenersAfterChange, _notifyHierarchyListenersBeforeChange, _propagateValue, _removeAttribute, _splitName, _stripNumericSuffix, addChangeListener, addDebugListener, addHierarchyListener, attributeDeleted, attributeList, attributeList, decorators, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getFullName, getModelErrorHandler, getName, getName, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, notifyOfNameChange, propagateValue, propagateValues, removeAttribute, removeChangeListener, removeDebugListener, removeHierarchyListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, validateSettables, workspace
-
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface ptolemy.actor.Actor
createReceivers, getCausalityInterface, getDirector, getExecutiveDirector, getManager, inputPortList, newReceiver, outputPortList
-
Methods inherited from interface ptolemy.kernel.util.Derivable
getDerivedLevel, getDerivedList, propagateValue
-
Methods inherited from interface ptolemy.actor.Executable
isFireFunctional, isStrict, iterate, stop, stopFire, terminate
-
Methods inherited from interface ptolemy.actor.Initializable
addInitializable, preinitialize, removeInitializable
-
Methods inherited from interface ptolemy.kernel.util.Nameable
description, getContainer, getDisplayName, getFullName, getName, getName, setName
-
-
-
-
Field Detail
-
separator
public StringParameter separator
A specification of the separator between items in the table. The default is "comma", which results in assuming that fields are separated by commas. If the value is changed to "tab", then a tab separator will be used. If the value is "semicolon", then a semicolon separator will be used. If the value is anything else, then the value of the parameter, whatever it is, will be the separator.
-
trimSpaces
public Parameter trimSpaces
If true, then trim spaces around each field name and value. This is a boolean that defaults to true. If you change it to false, then all spaces in the field names and values are preserved. Note that if there are spaces in the field names, then the value of the record cannot be read by the expression evaluator, so spaces in field names are not recommended.
-
-
Constructor Detail
-
CSVReader
public CSVReader(CompositeEntity container, java.lang.String name) throws IllegalActionException, NameDuplicationException
Construct an actor with the given container and name.- Parameters:
container
- The container.name
- The name of this actor.- Throws:
IllegalActionException
- If the actor cannot be contained by the proposed container.NameDuplicationException
- If the container already has an actor with this name.
-
-
Method Detail
-
attributeChanged
public void attributeChanged(Attribute attribute) throws IllegalActionException
If the specified attribute is separator then set a local variable with the value of the separator.- Overrides:
attributeChanged
in classLineReader
- Parameters:
attribute
- The attribute that has changed.- Throws:
IllegalActionException
- If the specified attribute is fileOrURL and the file cannot be opened, or the previously opened file cannot be closed; or if the attribute is numberOfLinesToSkip and its value is negative.
-
fire
public void fire() throws IllegalActionException
Output the data read in the preinitialize() or in the previous invocation of postfire(), if there is any.- Specified by:
fire
in interfaceExecutable
- Overrides:
fire
in classLineReader
- Throws:
IllegalActionException
- If there's no director.
-
wrapup
public void wrapup()
Wrapup execution of this actor. This method overrides the base class to discard the internal parser to save memory.- Specified by:
wrapup
in interfaceInitializable
- Overrides:
wrapup
in classLineReader
-
_defaultTypeConstraints
protected java.util.Set<Inequality> _defaultTypeConstraints()
Override the default to eliminate the default type constraints/.- Overrides:
_defaultTypeConstraints
in classTypedAtomicActor
- Returns:
- An empty set of type constraints
-
-