parseDeftemplate in Jess application. Can't provide the JessTokenStream - parsing

I'm implementing a methond in my application that uses the Jessp parser class in order to open a file and getting the deftemplates and deffacts inside of it. The problem is that when trying to obtain the result into a object variable, it asks on the constructor for a JessTokenStream. I tried to pass a JessToken, but then it complains about the type, that it should be e8. Searched through the Jess documentation but didn't found an explanation for the arguments, only the syntax of the constructor.
Anyone can help?.
Thanks in advance!!!

The class JessTokenStream is not public, so you can't actually call those parseXXX() methods. They are public for historical reasons but aren't actually usable by clients. They should actually be removed from the public interface.
Instead, use the two-argument form of parseExpression(), and then test the returned object to determine its type. Then you can do what you want with the returned object:
Rete engine = ...
Jesp jesp = ...
Object o = jesp.parseExpression(engine.getGlobalContext(), false);
if (o instanceof Deffacts) {
Deffacts d = (Deffacts) o;
for (int i = 0; i<d.getNFacts(); ++i) {
Fact f = d.getFact(i);
Deftemplate t = f.getDeftemplate();
System.out.println("Fact name is " + f.getName();
System.out.println("Fact name is " + f.getName();
for (String name: t.getSlotNames())
System.out.println("Slot " + name + " contains " + f.getSlotValue(name));
}
}

Related

performance issue with getProperties

I‘m new to this so I hope I get it right.
I‘m not exactly new to writing DXL but currently have a performance issue with calling getProperties from a Layout dxl column that is supposed to display outgoing links depending on a module attribute value of type Enum of the linked module.
The code basically works but takes extremely long to complete. Commenting out the getProperties call makes it as fast as it could be.
Yes, the call is written exactly as shown in DXL Ref manual.
Calling the attribute directly, using a module object and dot operator does not work either as it always returns the enums default value but not the actual.
Any ideas welcome...
EDIT added example code below
// couple of declarations snipped
string cond = "Enum selection here" // this is modified from actual code, to show the idea
string linkModName = "*"
ModuleProperties mp
for l in all(o->linkModName) do
{
otherVersion = targetVersion l
otherMod = module(otherVersion)
if (null otherMod || isDeleted otherMod) continue
othero = target l
if (null othero)
{
load(otherVersion,false)
}
getProperties(otherVersion, mp)
sTemp = mp.myAttr
if (sTemp == cond) continue
// further code snipped
}
I'm not 100% sure but I think there is/was a performance issue with module properties in some DOORS versions.
You might want to try the following, i.e. directly get the attribute from the loaded Module
[...]
othero = target l
Module m
if (null othero)
{
m = load(otherVersion,false)
} else {
m = module othero
}
sTemp = m.myAttr
[...]
Caution, I did not test this snippet.

checking an object in a nested link via dxl

I have the following situation.
I want to count in Module 1, how many objects are having links in links from Module 3.
example:
Module 1 Obj1 <- Module 2 Obj1 <- Module 3.Obj1
Module 1 Obj2 <- Module 2 Obj1 <- Module 3.Obj1
Module 1 Obj3 <- Module 2 Obj1 <- Module 3.Obj1
Module 1 Obj4 <- Module 2 Obj1
Module 1 Obj5 <- Module 2 Obj1
The count should return 3, in the above case.
Is it possible via DXL to follow a link, and then follow another link?
(not using the Wizard or DXL attributes)
Most important for me: knowing if somebody else did this and it's possible to do.
Please try the following DXL from within the module that has the incoming links. Before running the code:
make sure that you open the 'Edit DXL' window from the relevant module
set the string values assigned to global constant STR_LINK_MOD_FULLNAME (line 17) to the full pathname of the link module whose links you are interested in
set the string values assigned to global constant STR_SRC_MOD_FULLNAME (line 18) to the full pathname of the source formal module (Module 3, in your example) whose links you are interested in
You shouldn't need to change anything else to make it work.
N.B. I have not considered the implications of analysing links in all link modules by using the string "*" in place of a specific link module name in line 17 (see point 2, above).
I also haven't gone out of my way to explain the code, though I have tried to be nice and tidy up after myself where DOORS and DXL require it. Please feel free to reply with any questions on what I have done.
Kind regards,
Richard
//<CheckObjectInNestedLink.dxl>
/*
*/
///////////////
// Sanity check
if (null (current Module))
{
print "ERROR: this script must be run from a Formal Module."
}
///////////////////
// Global Constants
const string STR_LINK_MOD_FULLNAME = "/New Family Car Project/Admin/Satisfies" // the fullName of a single link module - results of using "*" have not been considered/tested
const string STR_SRC_MOD_FULLNAME = "/New Family Car Project/Architecture/Architectural Design" // The fullName of the desired source Formal Module
///////////////////
// Global Variables
Module modSource = null
Object objTarget = null
Object objSource = null
Link lkIn = null
Skip skLinkedMods = create()
Skip skObjsWithDesiredSource = create()
int intNoOfLinked = 0
//////////////////////
// Auxiliary Functions
void closeSourceMods ()
{
Module srcMod
for srcMod in skLinkedMods do
{
close(srcMod)
}
}
void openSourceMods (Object objWithLinks)
{
ModName_ srcModRef
Module srcMod
for srcModRef in (objWithLinks <- STR_LINK_MOD_FULLNAME) do
{
srcMod = read(fullName(srcModRef), false)
put(skLinkedMods, srcMod, srcMod)
}
}
void recurseFollowInLinks (Object objWithLinks)
{
openSourceMods(objWithLinks)
for lkIn in objWithLinks <- STR_LINK_MOD_FULLNAME do
{
openSourceMods(objWithLinks)
objSource = source(lkIn)
string strSrcModName = fullName(module(objSource))
if (strSrcModName == STR_SRC_MOD_FULLNAME)
{
bool blNewEntry = put(skObjsWithDesiredSource, objTarget, objTarget)
if (blNewEntry)
{
intNoOfLinked++
}
//print "put(skObjsWithDesiredSource, " identifier(objTarget) ", " identifier(objTarget) ")\n"
}
recurseFollowInLinks(objSource)
}
}
void checkObjectInNestedLink (Module modThis, string strSourceModuleFullname, string strLinkModuleFullName)
{
intNoOfLinked = 0
for objTarget in modThis do
{
recurseFollowInLinks(objTarget)
}
print "The following " intNoOfLinked " objects have direct or indirect links of type " STR_LINK_MOD_FULLNAME " from formal module " STR_SRC_MOD_FULLNAME ":\n"
for objTarget in skObjsWithDesiredSource do
{
print identifier(objTarget)
print "\n"
}
}
///////////////
// Main Program
checkObjectInNestedLink ((current Module), STR_SRC_MOD_FULLNAME, STR_LINK_MOD_FULLNAME)
closeSourceMods()
delete(skLinkedMods)
delete(skObjsWithDesiredSource)

Iterating multiple reasoned literals from the same property

The title may be a bit confusing but basically this is the problem: I am using Jena and a Pellet reasoner to produce property literals from a resource called Patient_Doug. The triple looks like this:
Patient_Doug-> hasSuggestion-> Literal inferred suggestion.
The problem is that the Protege Pellet reasoner comes up with three suggestions for Doug, because Doug is in a pretty bad way in hospital. The Protege reasoner suggests that Doug needs a Hi-Lo bed, an RF ID band and a bed closer to the nurse's station. Unfortunatly, in Jena, I can only get Hi-lo bed to print. Only one of 3 literals.
Here is some of the code.
OntModel model = ModelFactory.createOntologyModel( PelletReasonerFactory.THE_SPEC );
String ns = "http://altervista.org/owl/unit.owl#";
String inputFile = "c:\\jena\\acuity.owl";
InputStream in = FileManager.get().open(inputFile);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFile + " not found");
}
model.read(in,"");
model.prepare();
//inf and reasoner wont run unless i use hp libraries!
//asserted data properties
Individual ind = model.getIndividual(ns+"Patient_Doug");
OntProperty abcValue = model.getOntProperty("http://example.org/hasABCValue");
//inferred data properties
OntProperty suggestion = model.getOntProperty(ns+"hasSuggestion");
//print asserted data properties
System.out.println("Properties for patient "+ind.getLocalName().toString());
System.out.println( abcValue.getLocalName()+"= "+ind.getPropertyValue(abcValue).asLiteral().getInt());
//print inferenced data properties
StmtIterator it = ind.listProperties(suggestion);
//this iterator only prints one suggestion in an infinite loop
while (it.hasNext()) {
System.out.println("A posible suggestion= "+ind.getPropertyValue(suggestion).asLiteral().getString());
}
}
The code works fine but the iterator at the end only prints only one subggestion in an infinite loop.
I would be grateful for any suggestions.
Thanks.
This code works to iterate and print the many inferred hasSuggestions. The hasSuggestion SWRL rules are in the OWL ontology
OntModel model = ModelFactory.createOntologyModel( PelletReasonerFactory.THE_SPEC );
String ns = "http://altervista.org/owl/unit.owl#";
String inputFile = "c:\\jena\\acuity.owl";
InputStream in = FileManager.get().open(inputFile);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFile + " not found");
}
model.read(in,"");
model.prepare();
//inf and reasoner wont run unless i use hp libraries!
//asserted data properties
Individual ind = model.getIndividual(ns+"Patient_Doug");
OntProperty abcValue = model.getOntProperty("http://example.org/hasABCValue");
//inferred data properties
OntProperty suggestion = model.getOntProperty(ns+"hasSuggestion");
//print asserted data properties
System.out.println("Properties for patient "+ind.getLocalName().toString());
System.out.println( abcValue.getLocalName()+"= "+ind.getPropertyValue(abcValue).asLiteral().getInt());
for (StmtIterator j = ind.listProperties(suggestion); j.hasNext(); ) {
Statement s = j.next();
//System.out.println( " " + s.getPredicate().getLocalName() + " -> " );
System.out.println( "A possible suggestion... " + s.getLiteral().getLexicalForm());
}

What am I doing incorrectly to my approach to this function & its call?

I have a fairly simple nested table Aurora64.Chat containing a couple of functions (where the main Aurora64 class is initialized elsewhere but I inserted it here for completeness):
Aurora64 = {};
Aurora64.Chat = {
entityId = 0;
Init = function()
local entity; --Big long table here.
if (g_gameRules.class == "InstantAction") then
g_gameRules.game:SetTeam(3, entity.id); --Spectator, aka neutral.
end
entityId = Entity.id;
self:LogToSystem("Created chat entity '" .. entity.name .. "' with ID '" .. entity.id .. "'. It is now available for use.");
end
LogToSystem = function(msg)
System.LogAlways("$1[Aurora 64]$2 " .. msg);
end
}
The above code fails (checked with the Lua Demo) with the following:
input:14: '}' expected (to close '{' at line 3) near 'LogToSystem'
I have tracked it down to the LogToSystem function and its usage (if I remove the function and the one time it is used, the code compiles perfectly), and I thought it was to do with my use of use of concatenation (it wasn't).
I'm thinking I might have missed something simple, but I checked the documentation on functions and the function & its call seem to be written properly.
What exactly am I doing wrong here?
You are missing a comma before LogToSystem and you need to define it a bit differently (by adding self as an explicit parameter):
end,
LogToSystem = function(self, msg)
System.LogAlways("$1[Aurora 64]$2 " .. msg);
end
}
It's not possible to use the form obj:method with anonymous functions assigned to table fields; you can only use it with function obj:method syntax.

How can one to dynamically parse a CSV file using C# and the Smart Format Detector in FileHelpers 3.1?

As per in this FileHelpers 3.1 example, you can automatically detect a CSV file format using the FileHelpers.Detection.SmartFormatDetector class.
But the example goes no further. How do you use this information to dynamically parse a CSV file? It must have something to do with the DelimitedFileEngine but I cannot see how.
Update:
I figured out a possible way but had to resort to using reflection (which does not feel right). Is there another/better way? Maybe using System.Dynamic? Anyway, here is the code I have so far, it ain't pretty but it works:
// follows on from smart detector example
FileHelpers.Detection.RecordFormatInfo lDetectedFormat = formats[0];
Type lDetectedClass = lDetectedFormat.ClassBuilderAsDelimited.CreateRecordClass();
List<FieldInfo> lFieldInfoList = new List<FieldInfo>(lDetectedFormat.ClassBuilderAsDelimited.FieldCount);
foreach (FileHelpers.Dynamic.DelimitedFieldBuilder lField in lDetectedFormat.ClassBuilderAsDelimited.Fields)
lFieldInfoList.Add(lDetectedClass.GetField(lField.FieldName));
FileHelperAsyncEngine lFileEngine = new FileHelperAsyncEngine(lDetectedClass);
int lRecNo = 0;
lFileEngine.BeginReadFile(cReadingsFile);
try
{
while (true)
{
object lRec = lFileEngine.ReadNext();
if (lRec == null)
break;
Trace.WriteLine("Record " + lRecNo);
lFieldInfoList.ForEach(f => Trace.WriteLine(" " + f.Name + " = " + f.GetValue(lRec)));
lRecNo++;
}
}
finally
{
lFileEngine.Close();
}
As I use the SmartFormatDetector to determine the exact format of the incoming Delimited files you can use following appoach:
private DelimitedClassBuilder GetFormat(string file)
{
var detector = new FileHelpers.Detection.SmartFormatDetector();
var format = detector.DetectFileFormat(file);
return format.First().ClassBuilderAsDelimited;
}
private List<T> ConvertFile2Objects<T>(string file, out DelimitedFileEngine engine)
{
var format = GetSeperator(file); // Get Here your FormatInfo
engine = new DelimitedFileEngine(typeof(T)); //define your DelimitdFileEngine
//set some Properties of the engine with what you need
engine.ErrorMode = ErrorMode.SaveAndContinue; //optional
engine.Options.Delimiter = format.Delimiter;
engine.Options.IgnoreFirstLines = format.IgnoreFirstLines;
engine.Options.IgnoreLastLines = format.IgnoreLastLines;
//process
var ret = engine.ReadFileAsList(file);
this.errorCount = engine.ErrorManager.ErrorCount;
var err = engine.ErrorManager.Errors;
engine.ErrorManager.SaveErrors("errors.out");
//return records do here what you need
return ret.Cast<T>().ToList();
}
This is an approach I use in a project, where I only know that I have to process Delimited files of multiple types.
Attention:
I noticed that with the files I recieved the SmartFormatDetector has a problem with tab delimiter. Maybe this should be considered.
Disclaimer: This code is not perfected but in a usable state. Modification and/or refactoring is adviced.

Resources