Commit a80c458d authored by Thodoris Nestoridis's avatar Thodoris Nestoridis

5 step instances level, details about inference results

parent e52b17aa
......@@ -10,6 +10,10 @@
</nav>
<mat-grid-list cols="2">
<div class="first">
<div *ngIf="get_metrics(currentboilerplate.title)" style="margin-right: 50px;width: 90%;"
class="alert alert-warning" role="alert">
<p [innerHTML]="getinferdata()"></p>
</div>
<div *ngIf="currentboilerplate.id" class="edit-form">
<form ngNativeValidate>
<div class="form-group" style="display:flex; flex-direction: row; align-items: center">
......@@ -77,35 +81,35 @@
</div>
<mat-tab-group mat-align-tabs="center">
<div *ngFor="let section of systems| filter:searchText">
<div *ngIf= "section.Name == 'System' ">
<div *ngIf="section.Name == 'System' ">
<mat-tab label=Syntax>
<div *ngFor="let items of syntax| filter:searchText">
<mat-accordion>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>
{{ items.pos }}
</mat-panel-title>
<mat-panel-title>
{{ items.pos }}
</mat-panel-title>
</mat-expansion-panel-header>
<div *ngFor="let item of items.data| filter:searchText">
<mat-accordion>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>
{{ item.name }}
</mat-panel-title>
<mat-panel-description >
<h5>{{ item.details }}</h5>
</mat-panel-description>
</mat-expansion-panel-header>
<p>Details : {{item.explanation}}</p>
</mat-expansion-panel>
</mat-accordion>
</div>
</mat-expansion-panel>
</mat-accordion>
<div *ngFor="let item of items.data| filter:searchText">
<mat-accordion>
<mat-expansion-panel>
<mat-expansion-panel-header>
<mat-panel-title>
{{ item.name }}
</mat-panel-title>
<mat-panel-description>
<h5>{{ item.details }}</h5>
</mat-panel-description>
</mat-expansion-panel-header>
<p>Details : {{item.explanation}}</p>
</mat-expansion-panel>
</mat-accordion>
</div>
</mat-expansion-panel>
</mat-accordion>
</div>
</mat-tab>
</mat-tab>
</div>
<mat-tab label={{section.Name}}>
<div *ngFor="let item of section.TheClasses| filter:searchText">
......@@ -152,64 +156,165 @@
</mat-panel-title>
</mat-expansion-panel-header>
<p>{{sub.SubclassComment}}</p>
<div *ngIf=checklen(sub.SubSubClass)>
<h5><b>Subclasses</b></h5>
</div>
<div *ngFor="let subsub of sub.SubSubClass| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{ subsub.SubSubClass_name}}
</mat-panel-title>
</mat-expansion-panel-header>
<p>{{subsub.SubSubclassComment}}</p>
<div *ngIf=checklen(subsub.SubSubClass)>
<h5><b>Subclasses</b></h5>
</div>
<div *ngFor="let subsubsub of subsub.SubSubClass| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{ subsubsub.SubSubClass_name}}
</mat-panel-title>
</mat-expansion-panel-header>
<p>{{subsubsub.SubSubclassComment}}</p>
<div *ngIf=checklen(subsubsub.SubSubClass)>
<h5><b>Subclasses</b></h5>
</div>
<div *ngFor="let subsubsubsub of subsubsub.SubSubClass| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{ subsubsubsub.SubSubClass_name}}
</mat-panel-title>
</mat-expansion-panel-header>
<p>{{subsubsubsub.SubSubclassComment}} </p>
<ul> <button mat-button [matMenuTriggerFor]="menu"
[matMenuTriggerData]="{section: section.Name ,class: item.Class, subclass: sub.SubClass_name}"
[matMenuTriggerData]="{section: section.Name ,class: item.Class, subclass: sub.SubClass_name, subsubclass:subsub.SubSubClass_name , subsubsubclass: subsubsub.SubSubClass_name, subsubsubsubclass: subsubsubsub.SubSubClass_name}"
#menuTrigger>
<h5>Instances</h5>
</button>
<div *ngFor="let instansub of sub.InstanceOfSubclass| filter:searchText">
<div
*ngFor="let subsubsubsubinstansub of subsubsubsub.SubInstanceOfSubclass| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{ instansub.Instance}}
{{ subsubsubsubinstansub.Instance}}
</mat-panel-title>
</mat-expansion-panel-header>
<p>{{instansub.Comment}}</p>
<p>{{subsubsubsubinstansub.Comment}}</p>
</mat-expansion-panel>
</li>
</div>
</ul>
</mat-expansion-panel>
</li>
</div>
</ul>
<ul> <button mat-button [matMenuTriggerFor]="menu"
[matMenuTriggerData]="{section: section.Name ,class: item.Class, subclass: sub.SubClass_name, subsubclass:subsub.SubSubClass_name , subsubsubclass: subsubsub.SubSubClass_name}"
#menuTrigger>
<h5>Instances</h5>
</button>
<div *ngFor="let subsubsubinstansub of subsubsub.SubInstanceOfSubclass| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{ subsubsubinstansub.Instance}}
</mat-panel-title>
</mat-expansion-panel-header>
<p>{{subsubsubinstansub.Comment}}</p>
</mat-expansion-panel>
</li>
</div>
</ul>
</mat-expansion-panel>
</mat-accordion>
</li>
</div>
</div>
<ul>
<div *ngIf=checklen(section.GeneralInstances)>
<button mat-button [matMenuTriggerFor]="menu" [matMenuTriggerData]="{section: section.Name}" #menuTrigger>
<h4>Instances</h4>
<ul> <button mat-button [matMenuTriggerFor]="menu"
[matMenuTriggerData]="{section: section.Name ,class: item.Class, subclass: sub.SubClass_name, subsubclass:subsub.SubSubClass_name }"
#menuTrigger>
<h5>Instances</h5>
</button>
</div>
<div *ngFor="let genin of section.GeneralInstances| filter:searchText">
<div *ngFor="let subsubinstansub of subsub.SubInstanceOfSubclass| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{ subsubinstansub.Instance}}
</mat-panel-title>
</mat-expansion-panel-header>
<p>{{subsubinstansub.Comment}}</p>
</mat-expansion-panel>
</li>
</div>
</ul>
</mat-expansion-panel>
</li>
</div>
<ul> <button mat-button [matMenuTriggerFor]="menu"
[matMenuTriggerData]="{section: section.Name ,class: item.Class, subclass: sub.SubClass_name}"
#menuTrigger>
<h5>Instances</h5>
</button>
<div *ngFor="let instansub of sub.InstanceOfSubclass| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{genin.Instance}}
{{ instansub.Instance}}
</mat-panel-title>
</mat-expansion-panel-header>
{{genin.Comment}}
<p>{{instansub.Comment}}</p>
</mat-expansion-panel>
</li>
</div>
</ul>
</mat-expansion-panel>
</li>
</mat-tab>
</div>
</mat-tab-group>
<div *ngIf="!checklen(systems)">
<mat-spinner style="margin: auto;"></mat-spinner>
</ul>
</mat-expansion-panel>
</mat-accordion>
</div>
</div>
<ul>
<button mat-button [matMenuTriggerFor]="menu" [matMenuTriggerData]="{section: section.Name}" #menuTrigger>
<h4>Instances</h4>
</button>
<div *ngFor="let genin of section.GeneralInstances| filter:searchText">
<li>
<mat-expansion-panel hideToggle>
<mat-expansion-panel-header>
<mat-panel-title>
{{genin.Instance}}
</mat-panel-title>
</mat-expansion-panel-header>
{{genin.Comment}}
</mat-expansion-panel>
</li>
</div>
</ul>
</mat-tab>
</div>
</mat-tab-group>
<div *ngIf="!checklen(systems)">
<mat-spinner style="margin: auto;"></mat-spinner>
</div>
</div>
</mat-grid-list>
<mat-menu #menu="matMenu">
<ng-template let-class="class" let-section="section" let-subclass="subclass" matMenuContent><button mat-menu-item
(click)="openDialog(section, class, subclass)">Add Instances</button> </ng-template>
<ng-template let-class="class" let-section="section" let-subclass="subclass" let-subsubclass="subsubclass"
let-subsubsubclass="subsubsubclass" let-subsubsubsubclass="subsubsubsubclass" matMenuContent><button mat-menu-item
(click)="openDialog(section, class, subclass, subsubclass, subsubsubclass, subsubsubsubclass)">Add
Instances</button> </ng-template>
</mat-menu>
\ No newline at end of file
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Boilerplate } from 'src/app/models/boilerplate.model';
import { Boilerplate, InferenceResults } from 'src/app/models/boilerplate.model';
import { Sections } from 'src/app/models/boilerplate.model';
import { BoilerplateService } from 'src/app/services/boilerplate.service';
import { MainService } from 'src/app/services/main.service';
......@@ -23,6 +23,11 @@ export class BoilerplateDetailsComponent implements OnInit {
subjects: string[] = [];
systems?: Sections[];
infer: InferenceResults[] = [{}];
currentInfer?: InferenceResults = {
infer_group_of_boilerplate: "",
inference_data: "",
}
currentboilerplate: Boilerplate = {
group_of_boilerplate: this.route.snapshot.params.gb,
......@@ -58,6 +63,20 @@ export class BoilerplateDetailsComponent implements OnInit {
this.message = '';
this.getchoices(this.route.snapshot.params.gb);
this.getBoilerplate(this.route.snapshot.params.gb, this.route.snapshot.params.id);
this.getInfer();
}
getInfer(): void {
this.boilerplateService.getAllInfer(this.route.snapshot.params.gb)
.subscribe(
data => {
this.currentInfer = data[0];
this.infer = data;
},
error => {
console.log(error);
});
}
......@@ -118,7 +137,7 @@ export class BoilerplateDetailsComponent implements OnInit {
this.mainService.getdictionary(gb)
.subscribe(
data => {
// console.log(data[0].Dictionary_Data);
console.log(data[0].Dictionary_Data);
this.systems = data[0].Dictionary_Data
},
......@@ -126,6 +145,30 @@ export class BoilerplateDetailsComponent implements OnInit {
console.log(error);
});
}
details_metrics = ["isMissingConcept", "isMissingInstanceOf", "isMissingProducer", "isMissingState", "hasAmbiguousConcept", "hasAmbiguousConcept2",
"hasNoisyConcept", "hasOpaqueConcept", "isInconsistentTo"]
getinferdata(): any {
let message = ""
if (this.currentInfer && this.currentboilerplate.title) {
const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
for (let i of this.details_metrics) {
if (obj[i][0][this.currentboilerplate.title]?.length > 0) {
message += '<ul><li>' + obj[i][0]['Comment'] + ' <br> Invalid instances: ' + '<b>' + obj[i][0][this.currentboilerplate.title] + '</b>' + '</ul></li>'
}
}
return message
}
}
get_metrics(i: any): any {
if (this.currentInfer?.inference_data) {
const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
if (obj[i]) {
return true
}
}
return 0
}
checklen(i: any): any {
if (i) {
......@@ -139,10 +182,10 @@ export class BoilerplateDetailsComponent implements OnInit {
comment: "",
}
openDialog(section: any, classes: any, subclass: any) {
openDialog(section: any, classes: any, subclass: any, subsubclass: any, subsubsubclass: any, subsubsubsubclass: any) {
const dialogRef = this.dialog.open(CourseDialogComponentComponent, {
width: '500px',
data: { name: section + (classes ? ' : ' + classes : '') + (subclass ? ' : ' + subclass : ''), instance: this.currentDialog.instance, comment: this.currentDialog.comment },
data: { name: section + (classes ? ' : ' + classes : '') + (subclass ? ' : ' + subclass : '') + (subsubclass ? ' : ' + subsubclass : '') + (subsubsubclass ? ' : ' + subsubsubclass : '') + (subsubsubsubclass ? ' : ' + subsubsubsubclass : ''), instance: this.currentDialog.instance, comment: this.currentDialog.comment },
});
dialogRef.afterClosed().subscribe(result => {
......@@ -151,12 +194,14 @@ export class BoilerplateDetailsComponent implements OnInit {
result.instance = result.instance?.replace(/ /g, "_")
}
if (result.instance) {
this.addinstance = section + (classes ? ' : ' + classes : '') + (subclass ? ' : ' + subclass : '') + ' : ' + result.instance;
this.addinstance = section + (classes ? ' : ' + classes : '') + (subclass ? ' : ' + subclass : '') + (subsubclass ? ' : ' + subsubclass : '') + (subsubsubclass ? ' : ' + subsubsubclass : '') + (subsubsubsubclass ? ' : ' + subsubsubsubclass : '') + ' : ' + result.instance;
//console.log(this.addinstance);
this.mainService.setinstances(this.route.snapshot.params.gb, this.addinstance, (result.comment ? result.comment : " "))
.subscribe(
data => {
this.prefchild.getchoices(this.route.snapshot.params.gb);
this.mainchild.getmainchoices(this.route.snapshot.params.gb);
this.sufchild.getflowchoices(this.route.snapshot.params.gb);
//console.log(data);
},
error => {
......@@ -169,7 +214,7 @@ export class BoilerplateDetailsComponent implements OnInit {
value.TheClasses.forEach(function (value) {
if (classes == value.Class) {
//UI - Add instance of a Class (e.g instance for System : Vehicle)
if (!subclass) {
if (!subclass && !subsubclass) {
if (value.Instance_of_Class) {
value.Instance_of_Class.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
}
......@@ -179,7 +224,7 @@ export class BoilerplateDetailsComponent implements OnInit {
}
}
//UI - Add instance of a SubClass (e.g instance for System : Software : Plan)
if (subclass) {
if (subclass && !subsubclass) {
if (value.Subclass) {
value.Subclass.forEach(function (value) {
if (subclass == value.SubClass_name) {
......@@ -196,15 +241,101 @@ export class BoilerplateDetailsComponent implements OnInit {
})
}
}
if (subsubclass && !subsubsubclass) {
if (value.Subclass) {
value.Subclass.forEach(function (value) {
if (subclass == value.SubClass_name) {
if (value.SubSubClass) {
value.SubSubClass.forEach(function (value1) {
if (value1.SubSubClass_name == subsubclass) {
if (value1.SubInstanceOfSubclass) {
value1.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
} else {
value1.SubInstanceOfSubclass = [];
value1.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
}
}
})
}
}
})
}
}
if (subsubsubclass && !subsubsubsubclass) {
if (value.Subclass) {
value.Subclass.forEach(function (value) {
if (subclass == value.SubClass_name) {
if (value.SubSubClass) {
value.SubSubClass.forEach(function (value1) {
if (value1.SubSubClass_name == subsubclass) {
if (value1.SubSubClass) {
value1.SubSubClass.forEach(function (value2) {
if (value2.SubSubClass_name == subsubsubclass) {
if (value2.SubInstanceOfSubclass) {
value2.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
} else {
value2.SubInstanceOfSubclass = [];
value2.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
}
}
})
}
}
})
}
}
})
}
}
if (subsubsubsubclass) {
if (value.Subclass) {
value.Subclass.forEach(function (value) {
if (subclass == value.SubClass_name) {
if (value.SubSubClass) {
value.SubSubClass.forEach(function (value1) {
if (value1.SubSubClass_name == subsubclass) {
if (value1.SubSubClass) {
value1.SubSubClass.forEach(function (value2) {
if (value2.SubSubClass_name == subsubsubclass) {
if (value2.SubSubClass) {
value2.SubSubClass.forEach(function (value3) {
if (value3.SubInstanceOfSubclass) {
value3.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
} else {
value3.SubInstanceOfSubclass = [];
value3.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
}
})
}
}
})
}
}
})
}
}
})
}
}
}
});
}
if (!classes) { if (value.GeneralInstances) { value.GeneralInstances.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }) } }
else { value.GeneralInstances = []; value.GeneralInstances.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }); }
if (!classes) {
if (value.GeneralInstances) { value.GeneralInstances.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }) }
else { value.GeneralInstances = []; value.GeneralInstances.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }); }
}
}
})
}
this.mainchild.getmainchoices(this.route.snapshot.params.gb);
if (this.prefchild) { this.prefchild.getchoices(this.route.snapshot.params.gb); }
if (this.mainchild) { this.mainchild.getmainchoices(this.route.snapshot.params.gb); }
if (this.sufchild) { this.sufchild.getflowchoices(this.route.snapshot.params.gb); }
console.log('ooo', this.route.snapshot.params.gb);
} else { this.notifier.notify("warning", (JSON.stringify(error.error.detail))); }
});
//this.ngOnInit();
......@@ -215,38 +346,38 @@ export class BoilerplateDetailsComponent implements OnInit {
});
}
prefixs = [
{name: 'P1', details: "If/Unless <logical expression>", explanation: 'Expresses a logical condition. Paraphrases: in case, provided that, on condition that.'},
{name: 'P2', details: "As soon as <occuring functionality>", explanation: 'Expresses a temporal stimulation concerned with the point in time of an completed occuring functionality. Paraphrases: in the moment, immediately, once.'},
{name: 'P3', details: "As long as <occuring functionality>", explanation: 'Expresses a temporal condition concerned with a period. The prefix clause and the main clause take place simultaneously. Paraphrases: meanwhile'},
{ name: 'P1', details: "If/Unless <logical expression>", explanation: 'Expresses a logical condition. Paraphrases: in case, provided that, on condition that.' },
{ name: 'P2', details: "As soon as <occuring functionality>", explanation: 'Expresses a temporal stimulation concerned with the point in time of an completed occuring functionality. Paraphrases: in the moment, immediately, once.' },
{ name: 'P3', details: "As long as <occuring functionality>", explanation: 'Expresses a temporal condition concerned with a period. The prefix clause and the main clause take place simultaneously. Paraphrases: meanwhile' },
];
mains = [
{name: 'M1', details: "system/function shall [not] set [<quantifier>] item [to stateValue]", explanation: 'Sets item Paraphrases: initiate, reset, update.'},
{name: 'M2', details: "system/function shall [not] set state to stateValue", explanation: 'Sets state to value Paraphrases: initiate, reset, update.'},
{name: 'M3', details: "system/function shall [not] send [<quantifier>] item", explanation: 'Sends item Paraphrases: forward.'},
{name: 'M4', details: "system/function shall [not] receive [<quantifier>] item", explanation: 'Receives item Paraphrases: accept, acquire.'},
{name: 'M5', details: "system/function shall [not] ingest flow", explanation: 'Ingests flow. Paraphrases: get.'},
{name: 'M6', details: "system/function shall [not] emit flow", explanation: 'Emits flow. Paraphrases: produce.'},
{name: 'M7', details: "system shall [not] perform function", explanation: 'System requirement. Paraphrases: execute.'},
{name: 'M8', details: "function shall [not] invoke function", explanation: 'Function invokes another function. Paraphrases: call, request'},
{name: 'M9', details: "system shall [not] present interface [to system]", explanation: 'Presents interface. Paraphrases: provide'},
{name: 'M10', details: "system/interface shall [not] transfer flow/item", explanation: 'Transfers TraversingConcept. Paraphrases: transmit, broadcast'},
{name: 'M11', details: "system shall [not] interact with system [using <connection>] [as defined in <text>]", explanation: 'System requirement expressing interface interraction'},
{name: 'M12', details: "system shall [not] have state state [with values stateSet]", explanation: 'System requirement expressing system modes'},
{name: 'M13', details: "system state stateValue shall [not] have substate state [with values stateSet]", explanation: 'System requirement expressing system sub modes per mode'},
{name: 'M14', details: "system item shall [not] take values from stateSet", explanation: 'System requirement expressing item stateSet'},
{name: 'M15', details: "system item shall [not] be composed from item", explanation: 'System requirement expressing item decomposition stateSet'},
{name: 'M16', details: "system shall [not] contain system", explanation: 'System decomposition.'},
{ name: 'M1', details: "system/function shall [not] set [<quantifier>] item [to stateValue]", explanation: 'Sets item Paraphrases: initiate, reset, update.' },
{ name: 'M2', details: "system/function shall [not] set state to stateValue", explanation: 'Sets state to value Paraphrases: initiate, reset, update.' },
{ name: 'M3', details: "system/function shall [not] send [<quantifier>] item", explanation: 'Sends item Paraphrases: forward.' },
{ name: 'M4', details: "system/function shall [not] receive [<quantifier>] item", explanation: 'Receives item Paraphrases: accept, acquire.' },
{ name: 'M5', details: "system/function shall [not] ingest flow", explanation: 'Ingests flow. Paraphrases: get.' },
{ name: 'M6', details: "system/function shall [not] emit flow", explanation: 'Emits flow. Paraphrases: produce.' },
{ name: 'M7', details: "system shall [not] perform function", explanation: 'System requirement. Paraphrases: execute.' },
{ name: 'M8', details: "function shall [not] invoke function", explanation: 'Function invokes another function. Paraphrases: call, request' },
{ name: 'M9', details: "system shall [not] present interface [to system]", explanation: 'Presents interface. Paraphrases: provide' },
{ name: 'M10', details: "system/interface shall [not] transfer flow/item", explanation: 'Transfers TraversingConcept. Paraphrases: transmit, broadcast' },
{ name: 'M11', details: "system shall [not] interact with system [using <connection>] [as defined in <text>]", explanation: 'System requirement expressing interface interraction' },
{ name: 'M12', details: "system shall [not] have state state [with values stateSet]", explanation: 'System requirement expressing system modes' },
{ name: 'M13', details: "system state stateValue shall [not] have substate state [with values stateSet]", explanation: 'System requirement expressing system sub modes per mode' },
{ name: 'M14', details: "system item shall [not] take values from stateSet", explanation: 'System requirement expressing item stateSet' },
{ name: 'M15', details: "system item shall [not] be composed from item", explanation: 'System requirement expressing item decomposition stateSet' },
{ name: 'M16', details: "system shall [not] contain system", explanation: 'System decomposition.' },
];
suffixs = [
{name: 'S1', details: "<numerical-afirmative> j <closed-interval> [per <time-unit>]", explanation: ''},
{name: 'S2', details: "after/before flow", explanation: ''},
{name: 'S3', details: "[every/for a period of/within/for at least] <number> <time-unit> [from flow]", explanation: ''},
{name: 'S4', details: "at the beginning/at the end", explanation: ''},
{name: 'S5', details: "at even intervals", explanation: ''},
{name: 'S6', details: "sequentially", explanation: ''},
{ name: 'S1', details: "<numerical-afirmative> j <closed-interval> [per <time-unit>]", explanation: '' },
{ name: 'S2', details: "after/before flow", explanation: '' },
{ name: 'S3', details: "[every/for a period of/within/for at least] <number> <time-unit> [from flow]", explanation: '' },
{ name: 'S4', details: "at the beginning/at the end", explanation: '' },
{ name: 'S5', details: "at even intervals", explanation: '' },
{ name: 'S6', details: "concurently with/sequentially to <function>", explanation: '' },
];
syntax = [{pos:"Prefix", data: this.prefixs}, {pos:"Main", data: this.mains}, {pos:"Suffix", data: this.suffixs}]
syntax = [{ pos: "Prefix", data: this.prefixs }, { pos: "Main", data: this.mains }, { pos: "Suffix", data: this.suffixs }]
}
......@@ -46,8 +46,8 @@
<!-- Name Column -->
<ng-container matColumnDef="title_data">
<th mat-header-cell *matHeaderCellDef> Title </th>
<td mat-cell *matCellDef="let element" matTooltip={{get_metrics(element.title_data)}} > {{element.title_data}} <span
*ngIf="get_metrics(element.title_data).length > 0" matBadge={{get_metrics(element.title_data).length}}
<td mat-cell *matCellDef="let element" matTooltip={{get_metrics(element.title_data)}}> {{element.title_data}}
<span *ngIf="get_metrics(element.title_data).length > 0" matBadge={{get_metrics(element.title_data).length}}
matBadgeColor="warn" matBadgeSize="small" position="above"> &nbsp;&nbsp; </span>
</td>
</ng-container>
......
......@@ -156,19 +156,21 @@ export class BoilerplateListComponent implements OnInit {
this.boilerplateService.getAllInfer(this.route.snapshot.params.gb)
.subscribe(
data => {
console.log(data);
this.currentInfer = data[0];
this.infer = data;
const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
var final = []
for (let i of this.list_of_inference_metrics) {
if (obj[i] != undefined) {
if (data[0]) {
const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
var final = []
for (let i of this.list_of_inference_metrics) {
if (obj[i] != undefined) {
final.push({ value: obj[i].length, name: i })
}
final.push({ value: obj[i].length, name: i })
}
}
}
console.log(final);
//console.log(final);
this.chartOption.series = [{
type: 'pie',
radius: ['40%', '70%'],
......
<div fxLayoutAlign="end">
<mat-chip color="primary"> MAIN TEMPLATE : {{this.main}}</mat-chip>
<h2><span class="badge badge-secondary"> MAIN TEMPLATE : {{this.main}}</span></h2>
</div>
<div class="form-row">
<div class="col">
......@@ -91,9 +91,10 @@
<mat-label>Quantifier</mat-label>
<input placeholder="Pick one" aria-label="Number" matInput [formControl]="quantifierControl" type="text"
[matAutocomplete]="autoquantifier">
<mat-autocomplete autoActiveFirstOption #autoquantifier="matAutocomplete">
<mat-autocomplete autoActiveFirstOption #autoquantifier="matAutocomplete" showPanel="true"
[displayWith]="displayFn">
<mat-option *ngFor="let option of quantifierfilteredOptions | async" [value]="option">
{{option}}
{{option.split(" : ").pop()}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
......@@ -116,9 +117,10 @@
<mat-label>Number Unit</mat-label>
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="numunitControl"
[matAutocomplete]="autonumunit">
<mat-autocomplete autoActiveFirstOption #autonumunit="matAutocomplete">
<mat-autocomplete autoActiveFirstOption #autonumunit="matAutocomplete" showPanel="true"
[displayWith]="displayFn">
<mat-option *ngFor="let option of numunitfilteredOptions | async" [value]="option">
{{option}}
{{option.split(" : ").pop()}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
......
<div class="form-row">
<div class="col">
<form class="form-group form-inline" ngNativeValidate>
<mat-form-field class="example-full-width">
<mat-label>Suffix</mat-label>
<input type="text"
placeholder="Pick one"
aria-label="Number"
matInput
[formControl]="suffixControl"
required
[matAutocomplete]="autosuffix"
>
<mat-autocomplete autoActiveFirstOption #autosuffix="matAutocomplete">
<mat-option *ngFor="let option of suffixfilteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
<div class="col" >
<form class="form-group form-inline">
<mat-form-field class="example-full-width">
<mat-label>Numerical Value</mat-label>
<input type="text" matInput [(ngModel)]="currentsuffix.numerical" name="numerical">
</mat-form-field>
</form>
</div>
<div class="col">
<form class="form-group form-inline">
<mat-form-field class="example-full-width">
<mat-label>Unit</mat-label>
<input type="text"
placeholder="Pick one"
aria-label="Number"
matInput
[formControl]="mumerical_unitsControl"
[matAutocomplete]="automumerical_units"
>
<mat-autocomplete autoActiveFirstOption #automumerical_units="matAutocomplete">
<mat-option *ngFor="let option of mumerical_unitsfilteredOptions | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
<div class="col">
<form class="form-group form-inline">
<mat-form-field class="example-full-width">
<mat-label *ngIf="flowControl.value !=null">Flow : {{flowControl.value.slice(0, flowControl.value.indexOf(':'))}}</mat-label>
<mat-label>Flow</mat-label>
<input type="text"
placeholder="Pick one"
aria-label="Number"
matInput
[formControl]="flowControl"
[matAutocomplete]="autoflow"
>
<mat-autocomplete autoActiveFirstOption #autoflow="matAutocomplete" showPanel="true" [displayWith]="displayFn">
<mat-option *ngFor="let option of flowfilteredOptions | async" [value]="option">
{{option.split(" : ").pop()}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
<div class="col">
<form class="form-group form-inline" ngNativeValidate>
<mat-form-field class="example-full-width">
<mat-label *ngIf="this.suffixControl.value !=null">Suffix :{{this.suffixControl.value.slice(0,
this.suffixControl.value.indexOf(':'))}}</mat-label>
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="suffixControl" required
[matAutocomplete]="autosuffix">
<mat-autocomplete autoActiveFirstOption #autosuffix="matAutocomplete" showPanel="true"
[displayWith]="displayFn">
<mat-option *ngFor="let option of suffixfilteredOptions | async" [value]="option">
{{option.split(" : ").pop()}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
<div class="col">
<form class="form-group form-inline">
<mat-form-field class="example-full-width">
<mat-label>Numerical Value</mat-label>
<input type="text" matInput [(ngModel)]="currentsuffix.numerical" name="numerical">
</mat-form-field>
</form>
</div>
<div class="col">
<form class="form-group form-inline">
<mat-form-field class="example-full-width">
<mat-label *ngIf="this.mumerical_unitsControl.value !=null">Numerical Value
: {{this.mumerical_unitsControl.value.slice(0,
this.mumerical_unitsControl.value.indexOf(':'))}}</mat-label>
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="mumerical_unitsControl"
[matAutocomplete]="autonumsuffix">
<mat-autocomplete autoActiveFirstOption #autonumsuffix="matAutocomplete" showPanel="true"
[displayWith]="displayFn">
<mat-option *ngFor="let option of mumerical_unitsfilteredOptions | async" [value]="option">
{{option.split(" : ").pop()}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
<div class="col" *ngIf="this.mumerical_unitsControl.value !=null">
<form class="form-group form-inline"
[ngStyle]=" showflow(this.suffixControl.value) ? {'visibility': 'visible'} : {'visibility': 'hidden'}">
<mat-form-field class="example-full-width">
<mat-label *ngIf="flowControl.value !=null">Flow or Function : {{flowControl.value.slice(0,
flowControl.value.indexOf(':'))}}</mat-label>
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="flowControl" required
[matAutocomplete]="autoflow">
<mat-autocomplete autoActiveFirstOption #autoflow="matAutocomplete" showPanel="true" [displayWith]="displayFn">
<mat-option *ngFor="let option of flowfilteredOptions | async" [value]="option">
{{option.split(" : ").pop()}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</div>
</div>
\ No newline at end of file
......@@ -26,6 +26,7 @@ export class SuffixDetailsComponent implements OnInit {
flowControl = new FormControl();
flow: string[] = [];
flowfilteredOptions: Observable<string[]>;
flowControlisDivVisible = false
public static id: any[] = [];
private readonly notifier: NotifierService;
......@@ -61,7 +62,10 @@ export class SuffixDetailsComponent implements OnInit {
}
ngOnInit(): void {
this.getchoices();
//this.getchoices();
this.getflowchoices(this.route.snapshot.params.gb);
console.log('aaa', this.route.snapshot.params.gb);
this.getAllSuffix(this.route.snapshot.params.id);
}
......@@ -75,6 +79,16 @@ export class SuffixDetailsComponent implements OnInit {
return "";
}
showflow(option: string): boolean {
this.flowControlisDivVisible = false
if (option != null) {
let x = option.split(" : ");
if ((x[x.length - 2] == "") || (x[x.length - 1] == "")) { return false; }
if (x[x.length - 2] == 'EventRelated' || x[x.length - 2] == 'TimeRangeRelated' || x[x.length - 2] == 'ExecutionRelated') { this.flowControlisDivVisible = true; return true; }
}
return false;
}
private _filter(data: string[], value: string): string[] {
const filterValue = value.toLowerCase();
return data.filter(option => option.toLowerCase().includes(filterValue));
......@@ -119,7 +133,7 @@ export class SuffixDetailsComponent implements OnInit {
updateSuffix(): void {
this.currentsuffix.s_choices = this.suffixControl.value;
this.currentsuffix.mumerical_units = this.mumerical_unitsControl.value;
this.currentsuffix.flow = this.flowControl.value;
if (this.flowControlisDivVisible) { this.currentsuffix.flow = this.flowControl.value; } else { this.currentsuffix.flow = '' }
for (let i = 0; i < SuffixDetailsComponent.id.length; i++) {
this.suffixService.update(this.route.snapshot.params.id, SuffixDetailsComponent.id[i], this.currentsuffix)
.subscribe(
......@@ -133,32 +147,50 @@ export class SuffixDetailsComponent implements OnInit {
}
getchoices(): void {
this.suffixService.getsuffix()
getflowchoices(prefix_group: any): void {
this.suffixService.getsuffixflow(prefix_group)
.subscribe(
data => {
for (let x = 0; x < data.length; x++) {
if (this.suffix.indexOf(data[x][1]) == -1) {
this.suffix.push(data[x][1]);
}
}
//set flow choices
this.setflow(JSON.parse(data[0].flow_choices));
this.setflow(JSON.parse(data[0].function_choices));
this.setsuffix(JSON.parse(data[0].suffix_choices));
this.setmumerical_units(JSON.parse(data[0].number_unit_choices));
},
error => {
console.log(error);
});
this.suffixService.getnumunits()
.subscribe(
data => {
for (let x = 0; x < data.length; x++) {
if (this.mumerical_units.indexOf(data[x][1]) == -1) {
this.mumerical_units.push(data[x][1]);
}
}
},
error => {
console.log(error);
});
this.suffixService.getflow()
}
setflow(strIntoObj: any): void {
for (let x = 0; x < strIntoObj.length; x++) {
if (this.flow.indexOf(strIntoObj[x][1]) == -1) {
this.flow.push((strIntoObj[x][1]));
}
}
}
setsuffix(strIntoObj: any): void {
for (let x = 0; x < strIntoObj.length; x++) {
if (this.suffix.indexOf(strIntoObj[x][1]) == -1) {
this.suffix.push((strIntoObj[x][1]));
}
}
}
setmumerical_units(strIntoObj: any): void {
for (let x = 0; x < strIntoObj.length; x++) {
if (this.mumerical_units.indexOf(strIntoObj[x][1]) == -1) {
this.mumerical_units.push((strIntoObj[x][1]));
}
}
}
}
/*this.suffixService.getflow()
.subscribe(
data => {
for (let x = 0; x < data.length; x++) {
......@@ -169,8 +201,4 @@ export class SuffixDetailsComponent implements OnInit {
},
error => {
console.log(error);
});
}
}
});*/
\ No newline at end of file
......@@ -45,6 +45,27 @@ export class SubClasses {
SubClass_name?: any;
SubclassComment?: any
InstanceOfSubclass?: Instances[];
SubSubClass?: SubSubClasses[];
}
export class SubSubClasses {
SubSubClass_name?: any;
SubSubclassComment?: any
SubInstanceOfSubclass?: Instances[];
SubSubClass?:SubSubSubClasses[];
}
export class SubSubSubClasses {
SubSubClass_name?: any;
SubSubclassComment?: any
SubInstanceOfSubclass?: Instances[];
SubSubClass?:SubSubSubSubClasses[];
}
export class SubSubSubSubClasses {
SubSubClass_name?: any;
SubSubclassComment?: any
SubInstanceOfSubclass?: Instances[];
}
export class Instances {
......
......@@ -6,6 +6,7 @@ import { environment } from '../../environments/environment';
const baseUrl = environment.apiroot + 'api-auth/groupboilerplates/0/boilerplates/';
const Url = '/suffix/';
const baseUrl2 = environment.apiroot + 'api-auth/groupboilerplates/';
@Injectable({
providedIn: 'root'
......@@ -45,5 +46,9 @@ export class SuffixService {
getflow(): Observable<any> {
return this.http.get(environment.apiroot +`api-auth/suffix/choices/flow/`);
}
getsuffixflow(gb: any): Observable<any> {
return this.http.get(`${baseUrl2}${gb}`+`/prefix/choices/simpleprefix/`);
}
}
......@@ -45,11 +45,17 @@ MAIN_CHOICES = ( ("",""), ("M1", "M1"),
#FUNCTION_INSTANCES_COMMENTS = get_dmo_instance_and_comment("SAO#Function")
#
SHALL_CHOICES = ( ("shall", "shall"), ("shall not", "shall not"))
QUANTIFIER_CHOICES = ( ("None","None"), ("All", "All"), ("Only", "Only"),
("More Than", "More Than"), ("Less Than", "Less Than"), ("Exactly","Exactly"),
("At Least", "At Least"), ("At Most", "At Most")
)
NUMBER_UNITS_CHOICES = (("",""),("m/s","m/s"), ("m/s^2","m/s^2"), ("m/s^3","m/s^3"), ("rad","rad"), ("rad/s","rad/s"), ("Hz","Hz"), ("METERS","METERS"), ("KILOMETERS","KILOMETERS"), ("VOLT","VOLT"), ("Number", "Number"))
#QUANTIFIER_CHOICES = ( ("None","None"), ("All", "All"), ("Only", "Only"),
# ("More Than", "More Than"), ("Less Than", "Less Than"), ("Exactly","Exactly"),
# ("At Least", "At Least"), ("At Most", "At Most")
# )
#NUMBER_UNITS_CHOICES = (("",""),("m/s","m/s"), ("m/s^2","m/s^2"), ("m/s^3","m/s^3"), ("rad","rad"), ("rad/s","rad/s"), ("Hz","Hz"), ("METERS","METERS"), ("KILOMETERS","KILOMETERS"), ("VOLT","VOLT"), ("Number", "Number"))
##g = Graph()
#g.load('../../Ontologies/2022_AOCS.ttl', format="turtle")
#PREFIX_SYNTAX = get_prefix_syntax(g)
#S_CHOICES = get_instances_g("RBO#Preposition",g) + get_instances_g("RBO#NumericalAffirmative",g)
#print(S_CHOICES)
#ITEM
#ITEM_CHOICES = get_instances("SAO#Item")
#ITEM_CLASSES_COMMENTS = get_dmo_classes_and_comment("SAO#Item")
......@@ -91,7 +97,6 @@ NUMBER_UNITS_CHOICES = (("",""),("m/s","m/s"), ("m/s^2","m/s^2"), ("m/s^3","m/s^
#VERB_CHOICES = get_verb_instances("LO#Verb")
VERB_CHOICES = get_verb_file_and_instances("LO#Verb")
#test to add M
CLASS_CHOICES = (("SYSTEM","SYSTEM"), ("FUNCTION","FUNCTION"), ("SHALL","SHALL/SHALL NOT"),
("QUANTIFIER","QUANTIFIER"), ("NUMBER_UNITS","NUMBER_UNITS"), ("ITEM","ITEM"),
......
......@@ -36,6 +36,9 @@ LOGICAL_EXPRESSION = ( ("",""),
#Need fixing
#VERB_CHOICES_PREFIX = ( ("",""))
list_of_DSO = ["http://delab.csd.auth.gr/ontologies/2018/SAO#","http://delab.csd.auth.gr/ontologies/2018/DSO#", "http://delab.csd.auth.gr/ontologies/2018/DSO-AOCS#","http://delab.csd.auth.gr/ontologies/2018/RDO-instances#"]#,
list_of_RBO = ["http://delab.csd.auth.gr/ontologies/2018/LO#","http://delab.csd.auth.gr/ontologies/2018/RBO#","http://delab.csd.auth.gr/ontologies/2018/LO-instances#"]
#list_of_LO = ["http://delab.csd.auth.gr/ontologies/2018/LO#","http://delab.csd.auth.gr/ontologies/2018/RBO#","http://delab.csd.auth.gr/ontologies/2018/LO-instances#"]
#Must read this info from the Ontology
......@@ -106,15 +109,19 @@ def update_instances(instance):
g.load(instance.ontology_file, format="turtle")
#PREFIX_SYNTAX = get_prefix_syntax(g)
VERB_CHOICES_PREFIX = get_prefix_verbs(g)
SYSTEM_CHOICES = get_instances_g("SAO#System",g)
FUNCTION_CHOICES = get_instances_g("SAO#Function",g)
ITEM_CHOICES = get_instances_g("SAO#Item",g)
INTERFACE_CHOICES = get_instances_g("SAO#Interface",g)
CONNECTION_CHOICES = get_instances_g("SAO#Connection",g)
FLOW_CHOICES = get_instances_g("SAO#Flow",g)
STATE_CHOICES = get_instances_g("SAO#State",g)
STATE_SET_CHOICES = get_instances_g("SAO#StateSet",g)
STATE_VALUE_CHOICES =get_instances_g("SAO#StateValue",g)
SYSTEM_CHOICES = get_instances_g("SAO#System",g, list_of_DSO)
FUNCTION_CHOICES = get_instances_g("SAO#Function",g, list_of_DSO)
ITEM_CHOICES = get_instances_g("SAO#Item",g, list_of_DSO)
INTERFACE_CHOICES = get_instances_g("SAO#Interface",g, list_of_DSO)
CONNECTION_CHOICES = get_instances_g("SAO#Connection",g, list_of_DSO)
FLOW_CHOICES = get_instances_g("SAO#Flow",g, list_of_DSO)
STATE_CHOICES = get_instances_g("SAO#State",g, list_of_DSO)
STATE_SET_CHOICES = get_instances_g("SAO#StateSet",g, list_of_DSO)
STATE_VALUE_CHOICES =get_instances_g("SAO#StateValue",g, list_of_DSO)
NUMBER_UNITS_CHOICES = get_instances_g("RBO#NumberUnit",g, list_of_RBO)
QUANTIFIER_CHOICES = get_instances_g("RBO#Quantifier",g, list_of_RBO)
NUMERICAL_AFFIRMATIVE_CHOICES = get_instances_g("RBO#NumericalAffirmative",g, list_of_RBO)
S_CHOICES = get_instances_g("RBO#Preposition",g, list_of_RBO) + get_instances_g("RBO#NumericalAffirmative",g, list_of_RBO)
BoilerplateGroupClassesInstances.objects.filter(classes_instances_owner= instance.owner_infer, classes_instances_group_of_boilerplate = instance.infer_group_of_boilerplate).update(
prefix_choices = json.dumps(PREFIX_CHOICES), prefix_logcon_choices =json.dumps(LOGIC_CONNECTIVE), prefix_verb_choices =json.dumps(STATE_CHOICES + VERB_CHOICES_PREFIX),
main_class_choices =json.dumps(MAIN_CHOICES), system_choices = json.dumps(SYSTEM_CHOICES), function_choices =json.dumps(FUNCTION_CHOICES),
......
......@@ -18,16 +18,26 @@ SUFFIX_CHOICES = (("",""), ('S1', 'S1: <numerical-affirmative> j <closed-interva
)
NUMERICAL_AFFIRMATIVE_CHOICES = (("MORE THAN", "MORE THAN"), ("LESS THAN", "LESS THAN"), ("EXACTLY","EXACTLY"),
("AT LEAST", "AT LEAST"), ("AT MOST", "AT MOST"))
NUMBER_UNITS_CHOICES = (("",""),("m/s","m/s"), ("m/s^2","m/s^2"), ("m/s^3","m/s^3"), ("rad","rad"), ("rad/s","rad/s"), ("Hz","Hz"), ("METERS","METERS"), ("KILOMETERS","KILOMETERS"), ("VOLT","VOLT"))
TIME_UNITS_CHOICES = (("SECONDS","SECONDS"), ("MINUTES","MINUTES"), ("MILLISECONDS","MILLISECONDS"), ("CYCLES","CYCLES"))
FLOW_CHOICES = get_instances("SAO#Flow")
#NUMBER_UNITS_CHOICES = (("",""),("m/s","m/s"), ("m/s^2","m/s^2"), ("m/s^3","m/s^3"), ("rad","rad"), ("rad/s","rad/s"), ("Hz","Hz"), ("METERS","METERS"), ("KILOMETERS","KILOMETERS"), ("VOLT","VOLT"))
#TIME_UNITS_CHOICES = (("SECONDS","SECONDS"), ("MINUTES","MINUTES"), ("MILLISECONDS","MILLISECONDS"), ("CYCLES","CYCLES"))
#FLOW_CHOICES = get_instances("SAO#Flow")
# FLOW returns ()
S2_CHOICES = (("BEFORE","BEFORE"), ("AFTER","AFTER"))
S3_CHOICES = (("EVERY","EVERY"), ("FOR A PERIOD OF","FOR A PERIOD OF"), ("WITHIN", "WITHIN"), ("FOR AT LEAST", "FOR AT LEAST"))
S4_CHOICES = (("AT THE BEGINNING","AT THE BEGINNING"), ("AT THE END","AT THE END"))
S5_6_CHOICES = (("AT EVEN INTERVALS","AT EVEN INTERVALS"), ("SEQUENTIALLY","SEQUENTIALLY"))
S5_6_CHOICES = (("AT EVEN INTERVALS","AT EVEN INTERVALS"), ("SEQUENTIALLY","SEQUENTIALLY"))
#S_CHOICES = NUMERICAL_AFFIRMATIVE_CHOICES + S2_CHOICES + S3_CHOICES + S4_CHOICES + S5_6_CHOICES
S_CHOICES = NUMERICAL_AFFIRMATIVE_CHOICES + S2_CHOICES + S3_CHOICES + S4_CHOICES + S5_6_CHOICES
'''g = Graph()
g.load('../../Ontologies/2022_AOCS.ttl', format="turtle")
S_CHOICES = get_instances_g("RBO#Preposition",g) + get_instances_g("RBO#NumericalAffirmative",g)
FLOW_CHOICES=(("SECONDS","SECONDS"), ("MINUTES","MINUTES"), ("MILLISECONDS","MILLISECONDS"), ("CYCLES","CYCLES"))
NUMBER_UNITS_CHOICES=get_instances_g("LO#NumberUnit",g)
SYSTEM_CHOICES = get_instances_g("SAO#System",g)
print(SYSTEM_CHOICES)'''
def create_suffix(instance):
......@@ -49,13 +59,16 @@ class Suffix(models.Model):
boilerplate_of_suffix = models.ForeignKey('reqtool.Boilerplate', related_name='suffix_boilerplate', on_delete=models.CASCADE)
suffix_owner = models.ForeignKey(User, related_name='suffix_owner', on_delete=models.CASCADE)
#prefix templates
s_choices = models.CharField(choices=S_CHOICES, max_length=100, blank=True)
#s_choices = models.CharField(choices=S_CHOICES, max_length=100, blank=True)
s_choices = models.CharField(max_length=100, blank=True)
#if S1
numerical = models.CharField(blank=True, null=True, max_length=10)
mumerical_units = models.CharField(choices=NUMBER_UNITS_CHOICES + TIME_UNITS_CHOICES, max_length=100, blank=True)
#mumerical_units = models.CharField(choices=NUMBER_UNITS_CHOICES, max_length=100, blank=True)
mumerical_units = models.CharField(max_length=100, blank=True)
#time_units = models.CharField(choices=TIME_UNITS_CHOICES, max_length=100, blank=True)
#if S2/S3
flow = models.CharField(choices=FLOW_CHOICES, max_length=100, blank=True)
#flow = models.CharField(choices=FLOW_CHOICES, max_length=100, blank=True)
flow = models.CharField(max_length=100, blank=True)
#find suffix
suffix_choices = models.CharField(choices=SUFFIX_CHOICES, max_length=100, blank=True)
#custom suffix
......
import os, subprocess, shutil
from rdflib import Graph, BNode
from rdflib import XSD, Graph, BNode
from rdflib.namespace import RDFS
from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace
from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace, Literal
from reqman.apps.reqtool.rest_api.services.parse_ontologies import *
#HERE
......@@ -11,9 +11,12 @@ Ontology_file = "../../Ontologies/2022_AOCS.ttl"
list_of_inference_metrics = ["IncompleteRequirement", "AmbiguousRequirement",
"InconsistentRequirement","NoisyRequirement","OpaqueRequirement","RedundantRequirement"]
info_metric = ["isMissingConcept", "isMissingInstanceOf", "isMissingProducer", "isMissingState", "hasAmbiguousConcept", "hasAmbiguousConcept2",
"hasNoisyConcept", "hasOpaqueConcept", "isInconsistentTo"]
prefix_syntax = get_prefix_syntax(g)
main_syntax = get_main_sytax_inference()
main_syntax = get_main_sytax_inference(g)
def getclassofprefix(prefix):
return(findclassofprefix(prefix))
......@@ -79,7 +82,7 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
g.load('../../Ontologies/'+ontfile, format="turtle")
else :
g.load(ontfile, format="turtle")
#print(ontfile)
print(ontfile)
#remove the requirements from the RDO-instances
previous_req = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO-instances#")
g.remove((previous_req, None, None))
......@@ -88,27 +91,31 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
g.add((per_instances + title, RDF.type, rdo + 'Requirement'))
try:
if (boilerplate[i][0]['has_prefix'] == True): #If the requirement has Prefix
prefixmodel=["system_fun_item", "item_function_flow_statevalue"]
g.add((per_instances + title, rdo + 'hasPrefix', per_instances+(title+"_"+ prefix[i][0]['simple_prefix'])))
g.add((per_instances+(title+"_"+ prefix[i][0]['simple_prefix']), RDF.type, rbo + prefix[i][0]['simple_prefix']))
prefixsub_splitter = prefix[i][0]['system_fun_item'].split(" : ")
prefix_attr_splitter = prefix[i][0]['item_function_flow_statevalue'].split(" : ")
if (prefix_attr_splitter[0] == 'StateValue'):
prefix_verb_splitter = prefix[i][0]['state_or_verb'].split(" : ")
if (prefix_verb_splitter[0] == 'State'):
g.add( (per_instances+(title+"_"+ prefix[i][0]['simple_prefix']), rbo+"isRelatedToLogicalExpression", (per_instances+("SystemStateValueContraint_"+title))))
g.add((per_instances+("SystemStateValueContraint_"+title), RDF.type, (per_instances+("SystemStateValueContraint"))))
g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToState", lo + prefix_attr_splitter[1].strip()))
for j in prefixmodel:
if prefix[i][0][j] != "":
sub_instance_file, prefix_subject_splitter = getinstancefile(prefix[i][0][j], g)
g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedTo"+prefix_subject_splitter[0], URIRef(str(sub_instance_file))+"#"+ str(prefix_subject_splitter[len(prefix_subject_splitter) -1])))
g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToState", rbo + prefix_verb_splitter[len(prefix_verb_splitter)-1].strip()))
g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToSystem", rbo + prefixsub_splitter[len(prefixsub_splitter)-1].strip()))
g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToStateValue", rbo + prefix_attr_splitter[len(prefix_attr_splitter)-1].strip()))
elif(prefix_attr_splitter[0]=="StateValue"):
g.add( (per_instances+(title+"_"+ prefix[i][0]['simple_prefix']), rbo+"isRelatedToLogicalExpression", (per_instances+("ItemStateValueContraint_"+title))))
g.add((per_instances+("ItemStateValueContraint_"+title), RDF.type, (per_instances+("ItemStateValueContraint"))))
g.add((per_instances+("ItemStateValueContraint_"+title), rbo+"isRelatedToTraversingConcept", rbo + prefixsub_splitter[len(prefixsub_splitter)-1].strip()))
g.add((per_instances+("ItemStateValueContraint_"+title), rbo+"isRelatedToStateValue", rbo + prefix_attr_splitter[len(prefix_attr_splitter)-1].strip()))
else:
prefix_verb_splitter = prefix[i][0]['state_or_verb'].split(" : ")
g.add((per_instances+(title+"_"+ prefix[i][0]['simple_prefix']), rbo+"isRelatedToOccuringFunctionality", per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title)))
g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), RDF.type, (per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"))))
g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToAction", lo + prefix_verb_splitter[1].strip()))
for j in prefixmodel:
if prefix[i][0][j] != "":
sub_instance_file, prefix_subject_splitter = getinstancefile(prefix[i][0][j], g)
g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedTo"+prefix_subject_splitter[0], URIRef(str(sub_instance_file))+"#"+ str(prefix_subject_splitter[len(prefix_subject_splitter) -1])))
g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToAction", lo + prefix_verb_splitter[len(prefix_verb_splitter)-1].strip()))
g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToStimulus", rbo + prefixsub_splitter[len(prefixsub_splitter)-1].strip()))
if(prefix_attr_splitter[0]=='Item'):
g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToTraversingConcept", rbo + prefix_attr_splitter[len(prefix_attr_splitter)-1].strip()))
elif(prefix_attr_splitter[0]=='Function'):
g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToFunction", rbo + prefix_attr_splitter[len(prefix_attr_splitter)-1].strip()))
except:
raise APIException("The instances in Prefix of Boilerplate "+title+" are not exist in the Ontology")
try:
......@@ -125,11 +132,12 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
#mainmodel=["flow_function_interface_item_system_state_stateset", "state_item_before_verb", "statevalue_before_verb", "statevalue_system_connection_stateset"]
mainmodel=["flow_function_interface_item_system_state_stateset", "statevalue_system_connection_stateset"]
for j in mainmodel:
if ( main[i][0]['main_choices'] == 'M10'):
instance_file, splitter_1 = getinstancefile(main[i][0][j], g)
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToTraversingConcept", URIRef(str(instance_file))+"#"+ str(splitter_1[len(splitter_1) -1])))
elif main[i][0][j] != "":
instance_file, splitter_1 = getinstancefile(main[i][0][j], g)
if(main[i][0][j] != ""):
instance_file, splitter_1 = getinstancefile(main[i][0][j], g)
if ( splitter_1[0] =='Item' or splitter_1[0] =='Flow' ):
print(main[i][0][j])
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToTraversingConcept", URIRef(str(instance_file))+"#"+ str(splitter_1[len(splitter_1) -1])))
else :
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedTo"+splitter_1[0], URIRef(str(instance_file))+"#"+ str(splitter_1[len(splitter_1) -1])))
mainbeforeverbmodel=["state_item_before_verb", "statevalue_before_verb"]
for j in mainbeforeverbmodel:
......@@ -137,30 +145,99 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
instance_file, splitter_1 = getinstancefile(main[i][0][j], g)
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToSubject"+splitter_1[0], URIRef(str(instance_file))+"#"+ str(splitter_1[len(splitter_1) -1])))
if main[i][0]['quantifier'] != "":
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToQuantifier", (per_instances+(title+"_"+ (main[i][0]['quantifier']).replace(" ", "")))))
per = URIRef('http://delab.csd.auth.gr/ontologies/2018/LO#'+ (main[i][0]['quantifier']).replace(" ", ""))
quant = URIRef(rbo + "Quantifier") # Initial Value if not any
for s, p, o in g.triples((per, RDFS.subClassOf, None)): #subClassOf
#print(o)
if ('RBO' in o):
quant=o
g.add((per_instances+(title+"_"+ (main[i][0]['quantifier']).replace(" ", "")), RDF.type, quant))
g.add((per_instances+(title+"_"+ (main[i][0]['quantifier']).replace(" ", "")), rbo+"hasAdverb", lo + (main[i][0]['quantifier']).replace(" ", "")))
if main[i][0]['numerical'] != "":
g.add((per_instances+(title+"_"+ (main[i][0]['quantifier']).replace(" ", "")), rbo+"hasNumerical", URIRef(per_instances+(main[i][0]['quantifier']).replace(" ", "")+"_"+str(main[i][0]['numerical']))))
g.add((URIRef(per_instances+(main[i][0]['quantifier']).replace(" ", "")+"_"+str(main[i][0]['numerical'])), RDF.type, URIRef(rbo+"Numerical")))
quantimain= main[i][0]['quantifier'].split(':')
if(quantimain[len(quantimain)-2].strip() == "NonNumericalAffirmative"):
g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToQuantifier", lo+ (quantimain[len(quantimain)-1].strip())))
elif(quantimain[len(quantimain)-2].strip() == "Negative"):
g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToQuantifier", lo+ (quantimain[len(quantimain)-1].strip())))
elif ( quantimain[len(quantimain)-2].strip() == "ClosedInterval"):
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToQuantifier", (per_instances+(title+ "_Quantifier" ))))
g.add((per_instances+(title+ "_Quantifier" ), RDF.type, rbo+"ClosedInterval"))
g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToNumericalQuantifier", lo+quantimain[len(quantimain)-1].strip()))
#isRelatedToNumerical
g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToNumerical", per_instances+(title+ "_Quantifier_Numerical")))
g.add((per_instances+(title+ "_Quantifier_Numerical"), RDF.type , rbo+"Numerical" ))
if(main[i][0]["numerical"] !=""):
g.add((per_instances+(title+ "_Quantifier_Numerical"), rbo+"isRelatedToNumber", (Literal(suffix[i][0]["numerical"], datatype=XSD.float)) ))
#isRelatedToTimeUnit
if(main[i][0]["mumerical_units"]!=""):
g.add((per_instances+(title+ "_Quantifier_Numerical"), rbo+"isRelatedToNumberUnit", lo+numunit[len(numunit)-1].strip() ))
elif(quantimain[len(quantimain)-2].strip() == "NumericalAffirmative"):
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToQuantifier", (per_instances+(title+ "_Quantifier" ))))
g.add((per_instances+(title+ "_Quantifier" ), RDF.type, rbo+"NumericalAffirmative"))
g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToNumericalQuantifier", lo+quantimain[len(quantimain)-1].strip()))
#isRelatedToNumerical
g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToNumerical", per_instances+(title+ "_Quantifier_Numerical")))
g.add((per_instances+(title+ "_Quantifier_Numerical"), RDF.type , rbo+"Numerical" ))
if(main[i][0]["numerical"] !=""):
g.add((per_instances+(title+ "_Quantifier_Numerical"), rbo+"isRelatedToNumber", (Literal(suffix[i][0]["numerical"], datatype=XSD.float)) ))
#isRelatedToTimeUnit
if(main[i][0]["mumerical_units"]!=""):
g.add((per_instances+(title+ "_Quantifier_Numerical"), rbo+"isRelatedToNumberUnit", lo+numunit[len(numunit)-1].strip() ))
except:
raise APIException("The instances in MAIN of Boilerplate "+title+" are not exist in the Ontology")
try:
if (boilerplate[i][0]['has_suffix'] == True):
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ suffix[i][0]['suffix_choices'])))
#Need S1
#Need S2
#Need S3
g.add((per_instances+(title+"_"+ suffix[i][0]['suffix_choices']), RDF.type, URIRef(rbo+ suffix[i][0]['suffix_choices'])))
typesuffix = suffix[i][0]['s_choices'].split(':')
numunit=suffix[i][0]["mumerical_units"].split(":")
flowsuf=suffix[i][0]['flow'].split(':')
if(suffix[i][0]['s_choices']!= ""):
if ( typesuffix[len(typesuffix)-2].strip() == "NumericalAffirmative" or typesuffix[len(typesuffix)-2].strip() == "ClosedInterval"): #S1
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ "S1")))
g.add((per_instances+(title+"_"+ "S1"), RDF.type, URIRef(rbo+ "S1")))
#create Quantifier instance
g.add((per_instances+(title+"_"+ "S1"), rbo+"isRelatedToQuantifier", per_instances+(title+"_"+ "S1"+ "_Quantifier")))
if ( typesuffix[len(typesuffix)-2].strip() == "ClosedInterval"):
g.add((per_instances+(title+"_"+ "S1"+ "_Quantifier"), RDF.type, rbo+"ClosedInterval"))
else:
g.add((per_instances+(title+"_"+ "S1"+ "_Quantifier"), RDF.type, rbo+"NumericalAffirmative"))
#isRelatedToNumericalQuantifier
g.add((per_instances+(title+"_"+ "S1"+ "_Quantifier"), rbo+"isRelatedToNumericalQuantifier", lo+ typesuffix[len(typesuffix)-1].strip()))
#isRelatedToNumerical
g.add((per_instances+(title+"_"+ "S1"+ "_Quantifier"), rbo+"isRelatedToNumerical", per_instances+(title+"_"+ "S1"+ "_Quantifier_Numerical")))
g.add((per_instances+(title+"_"+ "S1"+ "_Quantifier_Numerical"), RDF.type , rbo+"Numerical" ))
if(suffix[i][0]["numerical"] !=""):
g.add((per_instances+(title+"_"+ "S1"+ "_Quantifier_Numerical"), rbo+"isRelatedToNumber", (Literal(suffix[i][0]["numerical"], datatype=XSD.float)) ))
#isRelatedToTimeUnit
if(suffix[i][0]["mumerical_units"]!=""):
if(numunit[len(numunit)-2].strip() == "TimeUnit"):
g.add((per_instances+(title+"_"+ "S1"), rbo+"isRelatedToTimeUnit", lo+numunit[len(numunit)-1].strip()))
else:
#isRelatedtoNumberUnit e.g kilometers
g.add((per_instances+(title+"_"+ "S1"+ "_Quantifier_Numerical"), rbo+"isRelatedToNumberUnit", lo+numunit[len(numunit)-1].strip() ))
if ( typesuffix[len(typesuffix)-2].strip() == "EventRelated"): #S2
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ "S2")))
g.add((per_instances+(title+"_"+ "S2"), RDF.type, URIRef(rbo+ "S2")))
g.add((per_instances+(title+"_"+ "S2"), rbo+"isRelatedToPreposition", lo+typesuffix[len(typesuffix)-1].strip()))
if(suffix[i][0]['flow'] !=""):
g.add((per_instances+(title+"_"+ "S2"), rbo+"isRelatedToTraversingConcept", lo+flowsuf[len(flowsuf)-1].strip()))
if ( typesuffix[len(typesuffix)-2].strip() == "TimeRangeRelated"): #S3
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ "S3")))
g.add((per_instances+(title+"_"+ "S3"), RDF.type, URIRef(rbo+ "S3")))
g.add((per_instances+(title+"_"+ "S3"), rbo+"isRelatedToPreposition", lo+typesuffix[len(typesuffix)-1].strip()))
if(suffix[i][0]["numerical"] !=""):
g.add((per_instances+(title+"_"+ "S3"), rbo+"isRelatedToNumber", (Literal(suffix[i][0]["numerical"], datatype=XSD.float)) ))
if(suffix[i][0]["mumerical_units"]!=""):
if(numunit[len(numunit)-2].strip() == "TimeUnit"):
g.add((per_instances+(title+"_"+ "S3"), rbo+"isRelatedToTimeUnit", lo+numunit[len(numunit)-1].strip()))
if(suffix[i][0]['flow'] !=""):
g.add((per_instances+(title+"_"+ "S3"), rbo+"isRelatedToTraversingConcept", lo+flowsuf[len(flowsuf)-1].strip()))
if ( typesuffix[len(typesuffix)-2].strip() == "TimeFrameRelated"): #S4
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ "S4")))
g.add((per_instances+(title+"_"+ "S4"), RDF.type, URIRef(rbo+ "S4")))
g.add((per_instances+(title+"_"+ "S4"), rbo+"isRelatedToPreposition", lo+typesuffix[len(typesuffix)-1].strip()))
if ( typesuffix[len(typesuffix)-2].strip() == "TimeSpaceRelated"): #S5
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ "S5")))
g.add((per_instances+(title+"_"+ "S5"), RDF.type, URIRef(rbo+ "S5")))
g.add((per_instances+(title+"_"+ "S5"), rbo+"isRelatedToPreposition", lo+typesuffix[len(typesuffix)-1].strip()))
if ( typesuffix[len(typesuffix)-2].strip() == "ExecutionRelated"): #S6
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ "S6")))
g.add((per_instances+(title+"_"+ "S6"), RDF.type, URIRef(rbo+ "S6")))
g.add((per_instances+(title+"_"+ "S6"), rbo+"isRelatedToPreposition", lo+typesuffix[len(typesuffix)-1].strip()))
if(flowsuf[0].strip() == 'Function'):
g.add((per_instances+(title+"_"+ "S3"), rbo+"isRelatedToFunction", lo+flowsuf[len(flowsuf)-1].strip()))
except:
raise APIException("The instances in SUFFIX of Boilerplate "+title+" are not exist in the Ontology")
#g.remove((per_instances + title, None, None))
try :
g.serialize(destination=ontfile+'.ttl', format='turtle')
return (ontfile)
......@@ -193,7 +270,19 @@ def shacl(ontotlogy_file):
#metrics_dict["IncompleteRequirement"] = [s]
get_title = str(s).split("#")
metrics_dict[inf_metr].append(get_title[1])
print(metrics_dict)
for inf_metr2 in info_metric:
metrics_dict[inf_metr2] = []
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO#"+inf_metr2)
req_dict={}
req_dict['Comment'] = ""
for scom, pcom, ocom in g.triples((p, RDFS.comment, None)):
req_dict['Comment'] = str(ocom)
req_dict[get_title[1]]=[]
for s1, p1, o1 in g.triples((s, p, None)):
get_title2 = str(o1).split("#")
req_dict[get_title[1]].append(get_title2[1])
metrics_dict[inf_metr2].append(req_dict)
print(metrics_dict)
return(metrics_dict)
......@@ -210,14 +299,13 @@ def findclassofprefix(listofprefix):
if (currentstate[0] == "State"):
if (currentsubjectspl[0] != "System"):
raise APIException("The Subject must be a System")
print(currentverb)
if (currentverb[1] == "is"):
if (currentsubjectspl[0] == "System"):
raise APIException("The Subject must be an Item")
#
for prefix in prefix_syntax:
for inprefix in prefix_syntax[prefix]:
if (currentverb[1] in prefix_syntax[prefix][inprefix]) or (currentstate[0] in prefix_syntax[prefix][inprefix]):
if (currentverb[1] in prefix_syntax[prefix][inprefix.split("_")[0]+"_Verbs"]) or (currentstate[0] in prefix_syntax[prefix][inprefix.split("_")[0]+"_Verbs"] or currentverb[1] =='is' ):
if currentsubject.split(":")[0].strip() in prefix_syntax[prefix][inprefix.split("_")[0]+"_Subject"]:
if currentattr.split(":")[0].strip() in prefix_syntax[prefix][inprefix.split("_")[0]+"_Attribute"]:
if listofprefix['prefix'] == "If":
......@@ -255,20 +343,20 @@ def findclassofmain(listofmain):
if (currenSubStateValue[0] != 'StateValue'):
classlist.append("ERROR")
return classlist
if (currenLast[0] == 'StateSet'):
if(currentattr[0] != 'State'):
if (currenLast[0].strip() == 'StateSet'):
if(currentattr[0].strip() != 'State'):
classlist.append("ERROR")
return classlist
if (currenLast[0] == 'Connection'):
if(currentattr[0] != 'System'):
if (currenLast[0].strip() == 'Connection'):
if(currentattr[0].strip() != 'System'):
classlist.append("ERROR")
return classlist
if (currenLast[0] == 'StateValue'):
if(currentattr[0] != 'Item'):
if (currenLast[0].strip() == 'StateValue'):
if(currentattr[0].strip() != 'Item' and currentattr[0].strip() != 'State'):
classlist.append("ERROR")
return classlist
if (currenLast[0] == 'System'):
if(currentattr[0] != 'Interface'):
if (currenLast[0].strip() == 'System'):
if(currentattr[0].strip() != 'Interface'):
classlist.append("ERROR")
return classlist
#
......@@ -284,5 +372,6 @@ def findclassofmain(listofmain):
if attrmain == currentattr[0].strip():
classlist.append('M'+str(i+1))
return(classlist)
from rdflib import Graph, BNode
from rdflib.namespace import RDFS
from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace
from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace, Literal
#from subprocess import call
......@@ -8,13 +8,16 @@ from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace
#Ontology_file = "../../Ontologies/Mokos_18_1_7_47.ttl"
#Ontology_file = "../../Ontologies/Autonomy_v1.ttl"
Ontology_file = "../../Ontologies/Autonomy_v1.ttl"
Ontology_file = "../../Ontologies/2022_AOCS.ttl"
#Ontology_file = "../../Ontologies/Autonomy_v1.ttl"
subClass_instances = "../../Ontologies/instances_subclass.txt"
#HERE
#list_of_DSO = ["http://delab.csd.auth.gr/ontologies/2018/SAO#","http://delab.csd.auth.gr/ontologies/2018/DSO#", "http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive#", "http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive-AVP#", "http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive-AVP-instances#","http://delab.csd.auth.gr/ontologies/2018/RDO-instances#"]
list_of_DSO = ["http://delab.csd.auth.gr/ontologies/2018/SAO#","http://delab.csd.auth.gr/ontologies/2018/DSO#", "http://delab.csd.auth.gr/ontologies/2018/DSO-AOCS#", "http://delab.csd.auth.gr/ontologies/2018/DSO-AOCS-instances#","http://delab.csd.auth.gr/ontologies/2018/RDO-instances#"]
list_of_DSO = ["http://delab.csd.auth.gr/ontologies/2018/SAO#","http://delab.csd.auth.gr/ontologies/2018/DSO#", "http://delab.csd.auth.gr/ontologies/2018/DSO-AOCS#", "http://delab.csd.auth.gr/ontologies/2018/DSO-AOCS-instances","http://delab.csd.auth.gr/ontologies/2018/RDO-instances#"]#,
list_of_rbo = ["http://delab.csd.auth.gr/ontologies/2018/RBO#"]
list_of_lo = ["http://delab.csd.auth.gr/ontologies/2018/LO#"]
#list_of_RMO = ["RMO", "RMO-instances", "DSO-AOCS-instances", "<http://delab.csd.auth.gr/ontologies/2018/RDO-instances"]
#list_of_RMO = ["RMO", "RMO-instances", "DSO-Automotive-AVP-instances", "<http://delab.csd.auth.gr/ontologies/2018/DSO-Automotive-AVP-instances"]
DSO = ["http://delab.csd.auth.gr/ontologies/2018/DSO#"]
......@@ -132,7 +135,7 @@ info_dict = {}
'''Get Instaces - return tuple'''
def get_instances_g(keyword, g):
def get_instances_g(keyword, g, list_of_DSO):
#get_file_and_instances(keyword)
keywordspl = keyword.split("#")
in_list = [keywordspl[len(keywordspl)-1]]
......@@ -147,6 +150,7 @@ def get_instances_g(keyword, g):
for uri in list_of_DSO:
per = URIRef(uri +extra)
for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
#print('res',s)
spl = s.split("#")
in_list.append(spl[len(spl) - 1])
for extra in in_list:
......@@ -177,6 +181,7 @@ def get_file_and_instances(keyword, g):
for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
spl = s.split("#")
in_list.append(spl[len(spl) - 1])
#print(in_list)
#find two layer down System: Subclass : Instance
for extra in in_list:
for uri in list_of_DSO:
......@@ -286,7 +291,6 @@ def get_dmo_classes_and_comment(keyword, g):
comment_class = (str(o).replace("\r","")).replace("\n","")
suclass_dict = {}
subclass_list = []
sub_ins_dict = {}
for uri in list_of_DSO:
subclas_name = ""
per2 = URIRef(uri +comment)
......@@ -309,13 +313,103 @@ def get_dmo_classes_and_comment(keyword, g):
for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)):
find_comment_instance = (str(m1).replace("\r","")).replace("\n","")
sub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": find_comment_instance}
sub_ins.append(sub_ins_dict)
suclass_dict = {'SubClass_name': subclas_name, 'SubclassComment':find_comment, 'InstanceOfSubclass': sub_ins}
sub_ins.append(sub_ins_dict)
###############################
sub_ins_dict = {}
subsuclass_dict = {}
subsubclass_list = []
for uris in list_of_DSO:
per2 = URIRef(uris +subclas_name)
for k1, l1, h1 in g.triples((None, RDFS.subClassOf, per2)):
spl1 = k1.split("#")
subsubclas_name = spl1[len(spl1) - 1]
kop = URIRef(uri + spl1[len(spl1) - 1])
subfind_comment = ""
subfind_comment_instance = ""
for q, w, m in g.triples((kop, RDFS.comment, None)):
subfind_comment = (str(m).replace("\r","")).replace("\n","")
subsub_ins_dict = {}
subsub_ins = []
for suburired in list_of_DSO:
per3 = URIRef(suburired + spl1[len(spl1) - 1])
for s2, p2, o2 in g.triples((None, RDF.type, per3)):
spl2 = s2.split("#")
for urired2 in list_of_DSO:
kop2 = URIRef(urired2 + spl2[len(spl2) - 1])
for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)):
subfind_comment_instance = (str(m1).replace("\r","")).replace("\n","")
subsub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": subfind_comment_instance}
subsub_ins.append(subsub_ins_dict)
#####################################################################
subsub_ins_dict = {}
subsubsuclass_dict = {}
subsubsubclass_list = []
for uris in list_of_DSO:
per2 = URIRef(uris +subsubclas_name)
for k1, l1, h1 in g.triples((None, RDFS.subClassOf, per2)):
spl1 = k1.split("#")
subsubsubclas_name = spl1[len(spl1) - 1]
kop = URIRef(uri + spl1[len(spl1) - 1])
subsubfind_comment = ""
subsubfind_comment_instance = ""
for q, w, m in g.triples((kop, RDFS.comment, None)):
subsubfind_comment = (str(m).replace("\r","")).replace("\n","")
subsubsub_ins_dict = {}
subsubsub_ins = []
for subsuburired in list_of_DSO:
per3 = URIRef(subsuburired + spl1[len(spl1) - 1])
for s2, p2, o2 in g.triples((None, RDF.type, per3)):
spl2 = s2.split("#")
for urired2 in list_of_DSO:
kop2 = URIRef(urired2 + spl2[len(spl2) - 1])
for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)):
subsubfind_comment_instance = (str(m1).replace("\r","")).replace("\n","")
subsubsub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": subsubfind_comment_instance}
subsubsub_ins.append(subsubsub_ins_dict)
#####################################################################
subsubsub_ins_dict = {}
subsubsubsuclass_dict = {}
subsubsubsubclass_list = []
for uris in list_of_DSO:
per2 = URIRef(uris + subsubsubclas_name)
for k1, l1, h1 in g.triples((None, RDFS.subClassOf, per2)):
spl1 = k1.split("#")
subsubsubsubclas_name = spl1[len(spl1) - 1]
kop = URIRef(uri + spl1[len(spl1) - 1])
subsubsubfind_comment = ""
subsubsubfind_comment_instance = ""
for q, w, m in g.triples((kop, RDFS.comment, None)):
subsubsubfind_comment = (str(m).replace("\r","")).replace("\n","")
subsubsubsub_ins_dict = {}
subsubsubsub_ins = []
for subsubsuburired in list_of_DSO:
per3 = URIRef( subsubsuburired + spl1[len(spl1) - 1])
for s2, p2, o2 in g.triples((None, RDF.type, per3)):
spl2 = s2.split("#")
for suburired2 in list_of_DSO:
kop2 = URIRef(suburired2 + spl2[len(spl2) - 1])
for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)):
subsubsubfind_comment_instance = (str(m1).replace("\r","")).replace("\n","")
subsubsubsub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": subsubsubfind_comment_instance}
subsubsubsub_ins.append(subsubsubsub_ins_dict)
subsubsubsuclass_dict = {'SubSubClass_name': subsubsubsubclas_name, 'SubSubclassComment':subsubsubfind_comment, 'SubInstanceOfSubclass': subsubsubsub_ins}
subsubsubsubclass_list.append(subsubsubsuclass_dict)
#####################################################################
subsubsuclass_dict = {'SubSubClass_name': subsubsubclas_name, 'SubSubclassComment':subsubfind_comment, 'SubInstanceOfSubclass': subsubsub_ins, 'SubSubClass': subsubsubsubclass_list}
subsubsubclass_list.append(subsubsuclass_dict)
#########################################################################
subsuclass_dict = {'SubSubClass_name': subsubclas_name, 'SubSubclassComment':subfind_comment, 'SubInstanceOfSubclass': subsub_ins, 'SubSubClass': subsubsubclass_list}
subsubclass_list.append(subsuclass_dict)
suclass_dict = {'SubClass_name': subclas_name, 'SubclassComment':find_comment, 'InstanceOfSubclass': sub_ins, 'SubSubClass' : subsubclass_list}
subclass_list.append(suclass_dict)
############################################
dmo_dic = {"Class": name_class, "Comment":comment_class, 'Subclass': subclass_list, 'Instance_of_Class':instance_list}
dic_list.append(dmo_dic)
if out_list_com:
Dictionary_Data = { "Name":section, "TheClasses" : dic_list, "GeneralInstances": dic_list_in}
#print(Dictionary_Data)
return Dictionary_Data
#return dic_list
else:
......@@ -330,6 +424,10 @@ def get_dmo_classes_and_comment(keyword, g):
return Dictionary_Data
#return dic_list_backup
#Classes of classes and Comments
def get_dmo_classes_of_classes_and_comment(keyword):
dmo_dic = {}
......@@ -447,24 +545,18 @@ def check_quantifier(bnodes_uriref):
'''Find Boilerplate Attribute - return list'''
def get_attribute(bnodes_uriref, subjects, related_subjects, verbs):
def get_attribute(main, bnodes_uriref, subjects, related_subjects, verbs):
bnodes = []
attribute_list = []
bnodes_uriref = [str(i) for i in bnodes_uriref]
#print(main, bnodes_uriref)
for attribute in bnodes_uriref:
if "isRelatedToSubject" in attribute:
pass
elif "isRelatedTo" in attribute:
tmp = attribute.split("#")
if tmp[1] != '':
tmp = tmp[1].split("isRelatedTo")
attribute_list.append(tmp[1])
#to be deleted in only exist isRelatedTo
elif "isRelatedto" in attribute:
tmp = attribute.split("#")
if tmp[1] != '':
tmp = tmp[1].split("isRelatedto")
attribute_list.append(tmp[1])
#if "isRelatedToSubject" in attribute:
# pass
if "isRelatedTo" in attribute:
attribute_list.append(attribute)
#print(main, attribute_list)
attribute_list = list(filter(("Action").__ne__, attribute_list))
attribute_list = list(filter(("Attribute").__ne__, attribute_list))
attribute_list = list(filter(("Quantity").__ne__, attribute_list))
......@@ -475,6 +567,7 @@ def get_attribute(bnodes_uriref, subjects, related_subjects, verbs):
attribute_list = list(filter(("TraversingConcept").__ne__, attribute_list))
tmp_list = []
#print(bnodes_uriref)
for i in bnodes_uriref:
if not "isRelatedTo" in i:
if not "isRelatedto" in i:
......@@ -503,40 +596,74 @@ def get_attribute(bnodes_uriref, subjects, related_subjects, verbs):
'''Find Main syntax - return a dict with the syntax'''
def get_main_sytax_inference():
def get_main_sytax_inference(g):
get_main = get_instances_list("RBO#Main")
main_dict = {}
for main in get_main:
main_dict[main] = {}
#main_dict[main]["Id"] = main
main_dict[main]["Subject"] = []
main_dict[main]["Related_to_Subject"] = []
main_dict[main]["Verbs"] = []
main_dict[main]["Quantifier"] = None
main_dict[main]["Attributes"] = []
bnodes = []
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main)
for s, p, o in g.triples((p, None, None)):
if isinstance(o, BNode):
bnodes.append(o)
bnodes.sort()
for bn in bnodes:
for objects in g.objects(subject=BNode(bn)):
if isinstance(objects, BNode):
bnodes.append(objects)
bnodes.sort()
bnodes_uriref = []
for bn in bnodes:
for objects in g.objects(subject=BNode(bn)):
if isinstance(objects, URIRef):
bnodes_uriref.append(objects)
#tmp_list = list(filter(("nil").__ne__, tmp_list))
main_dict[main] = {}
main_dict[main]["Subject"] = get_subjects(bnodes_uriref)
main_dict[main]["Related_to_Subject"] = get_related_to_subject(bnodes_uriref)
main_dict[main]["Verbs"] = get_verb(bnodes_uriref)
main_dict[main]["Quantifier"] = check_quantifier(bnodes_uriref)
main_dict[main]["Attributes"] = get_attribute(bnodes_uriref, main_dict[main]["Subject"], main_dict[main]["Related_to_Subject"], main_dict[main]["Verbs"])
#print( main_dict[main]["Subject"])
data = []
for o1, p1, s1 in g.triples((o, None, None)):
if isinstance(s1, URIRef):
data.append(str(s1))
if isinstance(s1, BNode):
for objects1 in g.objects(subject=BNode(s1)):
if isinstance(objects1, BNode):
for objects2 in g.objects(subject=BNode(objects1)):
if isinstance(objects2, URIRef):
data.append(str(objects2))
elif isinstance(objects2, BNode):
for objects3 in g.objects(subject=BNode(objects2)):
if isinstance(objects3, URIRef):
if(not 'nil' in str(objects3)):
data.append(str(objects3))
strings_with_substring_subState = [string for string in data if "isRelatedToSubjectState" in string]
if(len(strings_with_substring_subState) > 0):
tmp_list = [string for string in data if string not in strings_with_substring_subState]
for i in tmp_list:
i=i.split('#')
main_dict[main]["Related_to_Subject"].append(i[1])
strings_with_substring_subItem = [string for string in data if "isRelatedToSubjectItem" in string]
if(len(strings_with_substring_subItem) > 0 and len(strings_with_substring_subState)==0):
tmp_list = [string for string in data if string not in strings_with_substring_subItem]
for i in tmp_list:
i=i.split('#')
main_dict[main]["Related_to_Subject"].append(i[1])
strings_with_substring_sub = [string for string in data if "isRelatedToSubject" in string]
if(len(strings_with_substring_sub) > 0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
tmp_list = [string for string in data if string not in strings_with_substring_sub]
for i in tmp_list:
i=i.split('#')
main_dict[main]["Subject"].append(i[1])
strings_with_substring_verb = [string for string in data if "isRelatedToAction" in string]
if(len(strings_with_substring_verb) > 0 ):
tmp_list = [string for string in data if string not in strings_with_substring_verb]
for i in tmp_list:
for s, p, o in g.triples((None, RDF.type, URIRef(i))):
spl = s.split("#")
main_dict[main]["Verbs"].append(spl[1])
strings_with_substring_quan = [string for string in data if "isRelatedToQuantifier" in string]
if(len(strings_with_substring_quan) > 0):
main_dict[main]["Quantifier"] = True
strings_with_substring_attr = [string for string in data if "isRelatedTo" in string]
if(len(strings_with_substring_attr) > 0 and len(strings_with_substring_verb) == 0 and len(strings_with_substring_quan)==0 and len(strings_with_substring_sub)==0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
tmp_list = [string for string in data if string not in strings_with_substring_attr]
tmp_list2 = [string for string in tmp_list if "boolean" not in string]
for i in tmp_list2:
i=i.split('#')
main_dict[main]["Attributes"].append(i[1])
return main_dict
......@@ -546,36 +673,72 @@ def get_main_sytax():
main_dict = {}
main_dict_list = []
for main in get_main:
main_dict[main] = {}
main_dict[main]["Id"] = main
main_dict[main]["Subject"] = []
main_dict[main]["Related_to_Subject"] = []
main_dict[main]["Verbs"] = []
main_dict[main]["Quantifier"] = None
main_dict[main]["Attributes"] = []
bnodes = []
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main)
for s, p, o in g.triples((p, None, None)):
if isinstance(o, BNode):
bnodes.append(o)
bnodes.sort()
for bn in bnodes:
for objects in g.objects(subject=BNode(bn)):
if isinstance(objects, BNode):
bnodes.append(objects)
bnodes.sort()
bnodes_uriref = []
for bn in bnodes:
for objects in g.objects(subject=BNode(bn)):
if isinstance(objects, URIRef):
bnodes_uriref.append(objects)
main_dict[main] = {}
main_dict[main]["Id"] = main
main_dict[main]["Subject"] = get_subjects(bnodes_uriref)
main_dict[main]["Related_to_Subject"] = get_related_to_subject(bnodes_uriref)
main_dict[main]["Verbs"] = get_verb(bnodes_uriref)
main_dict[main]["Quantifier"] = check_quantifier(bnodes_uriref)
main_dict[main]["Attributes"] = get_attribute(bnodes_uriref, main_dict[main]["Subject"], main_dict[main]["Related_to_Subject"], main_dict[main]["Verbs"])
main_dict_list.append(main_dict[main])
data = []
for o1, p1, s1 in g.triples((o, None, None)):
if isinstance(s1, URIRef):
data.append(str(s1))
if isinstance(s1, BNode):
for objects1 in g.objects(subject=BNode(s1)):
if isinstance(objects1, BNode):
for objects2 in g.objects(subject=BNode(objects1)):
if isinstance(objects2, URIRef):
data.append(str(objects2))
elif isinstance(objects2, BNode):
for objects3 in g.objects(subject=BNode(objects2)):
if isinstance(objects3, URIRef):
if(not 'nil' in str(objects3)):
data.append(str(objects3))
strings_with_substring_subState = [string for string in data if "isRelatedToSubjectState" in string]
if(len(strings_with_substring_subState) > 0):
tmp_list = [string for string in data if string not in strings_with_substring_subState]
for i in tmp_list:
i=i.split('#')
main_dict[main]["Related_to_Subject"].append(i[1])
strings_with_substring_subItem = [string for string in data if "isRelatedToSubjectItem" in string]
if(len(strings_with_substring_subItem) > 0 and len(strings_with_substring_subState)==0):
tmp_list = [string for string in data if string not in strings_with_substring_subItem]
for i in tmp_list:
i=i.split('#')
main_dict[main]["Related_to_Subject"].append(i[1])
strings_with_substring_sub = [string for string in data if "isRelatedToSubject" in string]
if(len(strings_with_substring_sub) > 0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
tmp_list = [string for string in data if string not in strings_with_substring_sub]
for i in tmp_list:
i=i.split('#')
main_dict[main]["Subject"].append(i[1])
strings_with_substring_verb = [string for string in data if "isRelatedToAction" in string]
if(len(strings_with_substring_verb) > 0 ):
tmp_list = [string for string in data if string not in strings_with_substring_verb]
for i in tmp_list:
for s, p, o in g.triples((None, RDF.type, URIRef(i))):
spl = s.split("#")
main_dict[main]["Verbs"].append(spl[1])
strings_with_substring_quan = [string for string in data if "isRelatedToQuantifier" in string]
if(len(strings_with_substring_quan) > 0):
main_dict[main]["Quantifier"] = True
strings_with_substring_attr = [string for string in data if "isRelatedTo" in string]
if(len(strings_with_substring_attr) > 0 and len(strings_with_substring_verb) == 0 and len(strings_with_substring_quan)==0 and len(strings_with_substring_sub)==0 and len(strings_with_substring_subState) == 0 and len(strings_with_substring_subItem)==0):
tmp_list = [string for string in data if string not in strings_with_substring_attr]
tmp_list2 = [string for string in tmp_list if "boolean" not in string]
for i in tmp_list2:
i=i.split('#')
main_dict[main]["Attributes"].append(i[1])
main_dict_list.append(main_dict[main])
return main_dict_list
......@@ -599,58 +762,65 @@ def get_prefix_syntax(g):
for i in tmp:
subclass_data.append(i)
for pre in subclass_data:
tmp_list = []
tmp_list2 = find_triples(pre)
tmp_list2 = [str(i) for i in tmp_list2]
for i in tmp_list2:
tmp = i.split("#")
tmp_list.append(tmp[1])
tmp_list = list(filter(("nil").__ne__, tmp_list))
tmp_list = list(filter(("Restriction").__ne__, tmp_list))
tmp_list = list(filter(("Class").__ne__, tmp_list))
tmp_list = list(filter(("Action").__ne__, tmp_list))
tmp_list = list(filter(("Quantity").__ne__, tmp_list))
tmp_list = list(filter(("UnitOfMeasurement").__ne__, tmp_list))
isrelated = []
sub = []
for i in tmp_list:
if "isRelatedTo" in i:
isrelated.append(i)
else:
sub.append(i)
if len(sub)>1 :
prefix_dict[prefix][str(pre)+"_Verbs"] = []
prefix_dict[prefix][str(pre)+"_Attribute"] = []
prefix_dict[prefix][str(pre)+"_Subject"] = []
# if pre is StateValueConstraint we know that Atribute is StateValue
if "StateValue" in str(pre) and len(sub)>1:
prefix_dict[prefix][str(pre)+"_Attribute"].append("StateValue")
sub.remove("StateValue")
else:
for i in sub:
for j in isrelated:
if i in j:
if i not in prefix_dict[prefix][str(pre)+"_Attribute"]:
prefix_dict[prefix][str(pre)+"_Attribute"].append(i)
sub.remove(i)
#add verbs
if tmp_list2:
ver = get_verb(tmp_list2)
if (len(ver)==0):
prefix_dict[prefix][str(pre)+"_Verbs"].append('is')
else:
prefix_dict[prefix][str(pre)+"_Verbs"].extend(ver)
for j in tmp_list2:
if "LO" in str(j):
sub.remove(j.split("#")[1])
#Subjects are everything that is not a verb or an attribute - may some erros here
for newsub in sub:
if newsub not in prefix_dict[prefix][str(pre)+"_Subject"]:
if (len(prefix_dict[prefix][str(pre)+"_Attribute"]) == 0 and len(sub)>=2):
prefix_dict[prefix][str(pre)+"_Attribute"].append(sub[len(sub) -2])
sub.pop(len(sub) -2)
else:
prefix_dict[prefix][str(pre)+"_Subject"].append(newsub)
prefix_dict[prefix][str(pre)+"_Verbs"] = []
prefix_dict[prefix][str(pre)+"_Attribute"] = []
prefix_dict[prefix][str(pre)+"_Subject"] = []
prefix_dict[prefix][str(pre)+"_Quantifier"] = None
bnodes = []
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + pre)
for s, p, o in g.triples((p, None, None)):
if isinstance(o, BNode):
bnodes.append(o)
data = []
for o1, p1, s1 in g.triples((o, None, None)):
if isinstance(s1, URIRef):
data.append(str(s1))
if( 'syntaxOrder' in p1):
order = int(s1)
if isinstance(s1, BNode):
for objects1 in g.objects(subject=BNode(s1)):
if isinstance(objects1, BNode):
for objects2 in g.objects(subject=BNode(objects1)):
if isinstance(objects2, URIRef):
data.append(str(objects2))
elif isinstance(objects2, BNode):
for objects3 in g.objects(subject=BNode(objects2)):
if isinstance(objects3, URIRef):
if(not 'nil' in str(objects3)):
data.append(str(objects3))
strings_with_substring_subState = [string for string in data if "isRelatedToStimulus" in string]
if( (len(strings_with_substring_subState) > 0) and order == 0):
tmp_list = [string for string in data if string not in strings_with_substring_subState]
for i in tmp_list:
i=i.split('#')
prefix_dict[prefix][str(pre)+"_Subject"].append(i[1])
strings_with_substring_verb = [string for string in data if "isRelatedToAction" in string]
if(len(strings_with_substring_verb) > 0 ):
tmp_list = [string for string in data if string not in strings_with_substring_verb]
for i in tmp_list:
for s, p, o in g.triples((None, RDF.type, URIRef(i))):
spl = s.split("#")
prefix_dict[prefix][str(pre)+"_Verbs"].append(spl[1])
strings_with_substring_state = [string for string in data if "isRelatedToState" in string]
if(len(strings_with_substring_state) > 0 ):
tmp_list = [string for string in data if string not in strings_with_substring_state]
for i in tmp_list:
i = i.split("#")
prefix_dict[prefix][str(pre)+"_Verbs"].append(i[1])
strings_with_substring_quan = [string for string in data if "isRelatedToQuantifier" in string]
if(len(strings_with_substring_quan) > 0):
prefix_dict[prefix][str(pre)+"_Quantifier"] = True
strings_with_substring_attr = [string for string in data if "isRelatedTo" in string]
if(len(strings_with_substring_attr) > 0 and order==0 and len(strings_with_substring_verb) == 0 and len(strings_with_substring_quan)==0 and len(strings_with_substring_subState)==0 ):
tmp_list = [string for string in data if string not in strings_with_substring_attr]
for i in tmp_list:
i=i.split('#')
prefix_dict[prefix][str(pre)+"_Subject"].append(i[1])
elif(len(strings_with_substring_attr) > 0 and len(strings_with_substring_verb) == 0 and len(strings_with_substring_quan)==0 and len(strings_with_substring_subState)==0 ):
tmp_list = [string for string in data if string not in strings_with_substring_attr]
for i in tmp_list:
i=i.split('#')
prefix_dict[prefix][str(pre)+"_Attribute"].append(i[1])
return prefix_dict
......
......@@ -38,9 +38,9 @@ urlpatterns = [
path('main/choices/shall/', main_req_views.ShallChoicesViewSet.as_view(), name='mainshall'),
#SUFFIX CHOICES DATA
path('suffix/choices/suffix/', suffix_req_views.SuffixChoicesViewSet.as_view(), name='suffixsuffix'),
path('suffix/choices/numunits/', suffix_req_views.NumChoicesViewSet.as_view(), name='suffixnum'),
path('suffix/choices/flow/', suffix_req_views.FlowChoicesViewSet.as_view(), name='suffixflow'),
##path('suffix/choices/suffix/', suffix_req_views.SuffixChoicesViewSet.as_view(), name='suffixsuffix'),
#path('suffix/choices/numunits/', suffix_req_views.NumChoicesViewSet.as_view(), name='suffixnum'),
#path('suffix/choices/flow/', suffix_req_views.FlowChoicesViewSet.as_view(), name='suffixflow'),
#Dictionary
path('groupboilerplates/<int:groupboil>/dictionary/', main_req_views.DictionaryViewSet.as_view(), name='dictionary'),
......
......@@ -97,7 +97,9 @@ class MainDetailsAPIView(RetrieveUpdateDestroyAPIView):
if( instance['mumerical_units'] not in numunit_data):
raise APIException("MAIN : Instance of Number Unit does not exist")
curmain_choices = inference.getclassofmain(instance)
if curmain_choices[0] == 'ERROR':
if(curmain_choices==None):
raise APIException("Main choices not in [M1-M16]")
if (curmain_choices[0] == 'ERROR'):
raise APIException("Main choices not in [M1-M16]")
else:
instance = serializer.save(main_choices = curmain_choices[0])
......@@ -136,7 +138,7 @@ class MainChoicesAPIView(APIView):
#print(Dictdata.values('Dictionary_Data')[0]['Dictionary_Data'])
class_prefix = self.getClassontologyfile(g,es_instance)
for s, p, o in g.triples((URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , RDF.type, URIRef(class_prefix))):
for s, p, o in g.triples((URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#") + es_instance[len(es_instance)-1].strip() , RDF.type, URIRef(class_prefix))):
raise APIException("This instance already exist")
try:
g.add(( URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , RDF.type, URIRef(class_prefix) ))
......@@ -146,6 +148,7 @@ class MainChoicesAPIView(APIView):
raise APIException("Cannot Add instance")
tempDict = []
flag = 0
#PROBLEMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
for sao in Dictdata.values('Dictionary_Data')[0]['Dictionary_Data']:
if sao['Name'] == es_instance[0].strip():
for sao2 in sao['TheClasses']:
......@@ -154,22 +157,54 @@ class MainChoicesAPIView(APIView):
for sao3 in sao2['Subclass']:
if sao3['SubClass_name'] == es_instance[2].strip():
flag = 2
if(sao3 ['InstanceOfSubclass'] == ''):
sao3 ['InstanceOfSubclass'] = []
sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment })
else:
sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment })
print(sao3)
for sao4 in sao3['SubSubClass']:
if es_instance[3] and sao4['SubSubClass_name'] == es_instance[3].strip():
flag =3
for sao5 in sao4['SubSubClass']:
if es_instance[4] and sao5['SubSubClass_name'] == es_instance[4].strip():
flag =4
for sao6 in sao5['SubSubClass']:
if es_instance[5] and sao6['SubSubClass_name'] == es_instance[5].strip():
flag = 5
if(flag == 5):
if(sao6 ['SubInstanceOfSubclass'] == ''):
sao6 ['SubInstanceOfSubclass'] = []
sao6['SubInstanceOfSubclass'].append({"Instance": es_instance[6].strip(), "Comment": comment })
else:
sao6['SubInstanceOfSubclass'].append({"Instance": es_instance[6].strip(), "Comment": comment })
if(flag == 4):
if(sao5 ['SubInstanceOfSubclass'] == ''):
sao5 ['SubInstanceOfSubclass'] = []
sao5['SubInstanceOfSubclass'].append({"Instance": es_instance[5].strip(), "Comment": comment })
else:
sao5['SubInstanceOfSubclass'].append({"Instance": es_instance[5].strip(), "Comment": comment })
if(flag == 3):
if(sao4 ['SubInstanceOfSubclass'] == ''):
sao4 ['SubInstanceOfSubclass'] = []
sao4['SubInstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment })
else:
sao4['InstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment })
# SubSubClass_name
if(flag == 2):
if(sao3 ['InstanceOfSubclass'] == ''):
sao3 ['InstanceOfSubclass'] = []
sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment })
else:
sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment })
if (flag == 1):
if(sao2 ['Instance_of_Class'] == ''):
print('sao2')
sao2 ['Instance_of_Class'] = []
sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment })
else:
sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment })
if(flag==0):
sao['GeneralInstances'].append({"Instance": es_instance[1].strip(), "Comment": comment })
print('aaaaaaaaaaaaaaaaa', flag)
tempDict.append(sao)
Dictdata.update(Dictionary_Data= tempDict)
if(len(es_instance) == 2):
instance=es_instance[0] +': ' + instance
if (es_instance[0].strip() == 'System'):
m = data.values('system_choices')[0]['system_choices'][:-1]
if (len(m) ==1 ):
......@@ -204,13 +239,12 @@ class MainChoicesAPIView(APIView):
return HttpResponse('Update Instance')
if (es_instance[0].strip() == 'Flow'):
m = data.values('flow_choices')[0]['flow_choices'][:-1]
print('data',m)
if (len(m) ==1 ):
m+= '["'+instance+'","'+instance+'"]'+']'
else :
m+= ',["'+instance+'","'+instance+'"]'+']'
data.update(flow_choices = str(m))
print(m)
data.update(flow_choices = str(m))
return HttpResponse('Update Instance')
if (es_instance[0].strip() == 'State'):
m = data.values('state_choices')[0]['state_choices'][:-1]
......@@ -236,6 +270,14 @@ class MainChoicesAPIView(APIView):
m+= ',["'+instance+'","'+instance+'"]'+']'
data.update(state_value_choices = str(m))
return HttpResponse('Update Instance')
if (es_instance[0].strip() == 'Connection'):
m = data.values('connection_choices')[0]['connection_choices'][:-1]
if (len(m) ==1 ):
m+= '["'+instance+'","'+instance+'"]'+']'
else :
m+= ',["'+instance+'","'+instance+'"]'+']'
data.update(connection_choices = str(m))
return HttpResponse('Update Instance')
......@@ -248,10 +290,18 @@ class MainChoicesAPIView(APIView):
raise APIException("There is no file for instances")
def getClassontologyfile(self, g, es_instance):
for ns_prefix, namespace in g.namespaces():
for s, p, o in g.triples((URIRef( namespace+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
return URIRef( namespace+ es_instance[len(es_instance)-2].strip() )
raise APIException("There is no Class in the Ontology ")
if(len(es_instance) == 2 ):
for ns_prefix, namespace in g.namespaces():
for s, p, o in g.triples((URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
print(p,s)
return URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() )
raise APIException("There is no Class in the Ontology ")
else:
for ns_prefix, namespace in g.namespaces():
for s, p, o in g.triples((URIRef( namespace+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
return URIRef( namespace+ es_instance[len(es_instance)-2].strip() )
raise APIException("There is no Class in the Ontology ")
......
......@@ -14,8 +14,8 @@ from reqman.apps.reqtool.rest_api.services import fuseki
from rest_framework.response import Response
from rest_framework.views import APIView
from reqman.apps.reqtool.models.suffix_req import S_CHOICES, NUMBER_UNITS_CHOICES, TIME_UNITS_CHOICES, FLOW_CHOICES
from reqman.apps.reqtool.models.suffix_req import NUMERICAL_AFFIRMATIVE_CHOICES, S2_CHOICES, S3_CHOICES, S4_CHOICES, S5_6_CHOICES
#from reqman.apps.reqtool.models.suffix_req import S_CHOICES, NUMBER_UNITS_CHOICES, TIME_UNITS_CHOICES, FLOW_CHOICES
#from reqman.apps.reqtool.models.suffix_req import NUMERICAL_AFFIRMATIVE_CHOICES, S2_CHOICES, S3_CHOICES, S4_CHOICES, S5_6_CHOICES
from reqman.apps.reqtool.models.requirements import BoilerplateData
......@@ -77,42 +77,6 @@ class SuffixDetailsAPIView(RetrieveUpdateDestroyAPIView):
instance.delete()
def getclassofsuffix(self, suffix):
for sys in NUMERICAL_AFFIRMATIVE_CHOICES:
if sys[0] == suffix:
return ("S1")
for sys in S2_CHOICES:
if sys[0] == suffix:
return ("S2")
for sys in S3_CHOICES:
if sys[0] == suffix:
return ("S3")
for sys in S4_CHOICES:
if sys[0] == suffix:
return ("S4")
#special case only one option for S5, S6
if S5_6_CHOICES[0][0] == suffix:
return ("S5")
if S5_6_CHOICES[1][0] == suffix:
return ("S6")
return ("S1")
class SuffixChoicesViewSet(APIView):
def get(self, request):
response = Response(S_CHOICES)
return response
class NumChoicesViewSet(APIView):
def get(self, request):
response = Response(NUMBER_UNITS_CHOICES+TIME_UNITS_CHOICES)
return response
class FlowChoicesViewSet(APIView):
def get(self, request):
response = Response(FLOW_CHOICES)
return response
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment