Commit a80c458d authored by Thodoris Nestoridis's avatar Thodoris Nestoridis

5 step instances level, details about inference results

parent e52b17aa
...@@ -10,6 +10,10 @@ ...@@ -10,6 +10,10 @@
</nav> </nav>
<mat-grid-list cols="2"> <mat-grid-list cols="2">
<div class="first"> <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"> <div *ngIf="currentboilerplate.id" class="edit-form">
<form ngNativeValidate> <form ngNativeValidate>
<div class="form-group" style="display:flex; flex-direction: row; align-items: center"> <div class="form-group" style="display:flex; flex-direction: row; align-items: center">
...@@ -77,35 +81,35 @@ ...@@ -77,35 +81,35 @@
</div> </div>
<mat-tab-group mat-align-tabs="center"> <mat-tab-group mat-align-tabs="center">
<div *ngFor="let section of systems| filter:searchText"> <div *ngFor="let section of systems| filter:searchText">
<div *ngIf= "section.Name == 'System' "> <div *ngIf="section.Name == 'System' ">
<mat-tab label=Syntax> <mat-tab label=Syntax>
<div *ngFor="let items of syntax| filter:searchText"> <div *ngFor="let items of syntax| filter:searchText">
<mat-accordion> <mat-accordion>
<mat-expansion-panel> <mat-expansion-panel>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> <mat-panel-title>
{{ items.pos }} {{ items.pos }}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<div *ngFor="let item of items.data| filter:searchText"> <div *ngFor="let item of items.data| filter:searchText">
<mat-accordion> <mat-accordion>
<mat-expansion-panel> <mat-expansion-panel>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> <mat-panel-title>
{{ item.name }} {{ item.name }}
</mat-panel-title> </mat-panel-title>
<mat-panel-description > <mat-panel-description>
<h5>{{ item.details }}</h5> <h5>{{ item.details }}</h5>
</mat-panel-description> </mat-panel-description>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>Details : {{item.explanation}}</p> <p>Details : {{item.explanation}}</p>
</mat-expansion-panel> </mat-expansion-panel>
</mat-accordion> </mat-accordion>
</div> </div>
</mat-expansion-panel> </mat-expansion-panel>
</mat-accordion> </mat-accordion>
</div> </div>
</mat-tab> </mat-tab>
</div> </div>
<mat-tab label={{section.Name}}> <mat-tab label={{section.Name}}>
<div *ngFor="let item of section.TheClasses| filter:searchText"> <div *ngFor="let item of section.TheClasses| filter:searchText">
...@@ -152,64 +156,165 @@ ...@@ -152,64 +156,165 @@
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>{{sub.SubclassComment}}</p> <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" <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> #menuTrigger>
<h5>Instances</h5> <h5>Instances</h5>
</button> </button>
<div *ngFor="let instansub of sub.InstanceOfSubclass| filter:searchText"> <div
*ngFor="let subsubsubsubinstansub of subsubsubsub.SubInstanceOfSubclass| filter:searchText">
<li> <li>
<mat-expansion-panel hideToggle> <mat-expansion-panel hideToggle>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> <mat-panel-title>
{{ instansub.Instance}} {{ subsubsubsubinstansub.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>{{instansub.Comment}}</p> <p>{{subsubsubsubinstansub.Comment}}</p>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </div>
</ul> </ul>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </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-expansion-panel>
</mat-accordion> </li>
</div> </div>
</div> <ul> <button mat-button [matMenuTriggerFor]="menu"
<ul> [matMenuTriggerData]="{section: section.Name ,class: item.Class, subclass: sub.SubClass_name, subsubclass:subsub.SubSubClass_name }"
<div *ngIf=checklen(section.GeneralInstances)> #menuTrigger>
<button mat-button [matMenuTriggerFor]="menu" [matMenuTriggerData]="{section: section.Name}" #menuTrigger> <h5>Instances</h5>
<h4>Instances</h4>
</button> </button>
</div> <div *ngFor="let subsubinstansub of subsub.SubInstanceOfSubclass| filter:searchText">
<div *ngFor="let genin of section.GeneralInstances| 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> <li>
<mat-expansion-panel hideToggle> <mat-expansion-panel hideToggle>
<mat-expansion-panel-header> <mat-expansion-panel-header>
<mat-panel-title> <mat-panel-title>
{{genin.Instance}} {{ instansub.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
{{genin.Comment}} <p>{{instansub.Comment}}</p>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </div>
</ul> </ul>
</mat-expansion-panel>
</li>
</mat-tab>
</div> </div>
</mat-tab-group> </ul>
<div *ngIf="!checklen(systems)"> </mat-expansion-panel>
<mat-spinner style="margin: auto;"></mat-spinner> </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> </div>
</ul>
</mat-tab>
</div>
</mat-tab-group>
<div *ngIf="!checklen(systems)">
<mat-spinner style="margin: auto;"></mat-spinner>
</div>
</div> </div>
</mat-grid-list> </mat-grid-list>
<mat-menu #menu="matMenu"> <mat-menu #menu="matMenu">
<ng-template let-class="class" let-section="section" let-subclass="subclass" matMenuContent><button mat-menu-item <ng-template let-class="class" let-section="section" let-subclass="subclass" let-subsubclass="subsubclass"
(click)="openDialog(section, class, subclass)">Add Instances</button> </ng-template> 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> </mat-menu>
\ No newline at end of file
import { Component, OnInit, ViewChild } from '@angular/core'; import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; 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 { Sections } from 'src/app/models/boilerplate.model';
import { BoilerplateService } from 'src/app/services/boilerplate.service'; import { BoilerplateService } from 'src/app/services/boilerplate.service';
import { MainService } from 'src/app/services/main.service'; import { MainService } from 'src/app/services/main.service';
...@@ -23,6 +23,11 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -23,6 +23,11 @@ export class BoilerplateDetailsComponent implements OnInit {
subjects: string[] = []; subjects: string[] = [];
systems?: Sections[]; systems?: Sections[];
infer: InferenceResults[] = [{}];
currentInfer?: InferenceResults = {
infer_group_of_boilerplate: "",
inference_data: "",
}
currentboilerplate: Boilerplate = { currentboilerplate: Boilerplate = {
group_of_boilerplate: this.route.snapshot.params.gb, group_of_boilerplate: this.route.snapshot.params.gb,
...@@ -58,6 +63,20 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -58,6 +63,20 @@ export class BoilerplateDetailsComponent implements OnInit {
this.message = ''; this.message = '';
this.getchoices(this.route.snapshot.params.gb); this.getchoices(this.route.snapshot.params.gb);
this.getBoilerplate(this.route.snapshot.params.gb, this.route.snapshot.params.id); 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 { ...@@ -118,7 +137,7 @@ export class BoilerplateDetailsComponent implements OnInit {
this.mainService.getdictionary(gb) this.mainService.getdictionary(gb)
.subscribe( .subscribe(
data => { data => {
// console.log(data[0].Dictionary_Data); console.log(data[0].Dictionary_Data);
this.systems = data[0].Dictionary_Data this.systems = data[0].Dictionary_Data
}, },
...@@ -126,6 +145,30 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -126,6 +145,30 @@ export class BoilerplateDetailsComponent implements OnInit {
console.log(error); 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 { checklen(i: any): any {
if (i) { if (i) {
...@@ -139,10 +182,10 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -139,10 +182,10 @@ export class BoilerplateDetailsComponent implements OnInit {
comment: "", 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, { const dialogRef = this.dialog.open(CourseDialogComponentComponent, {
width: '500px', 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 => { dialogRef.afterClosed().subscribe(result => {
...@@ -151,12 +194,14 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -151,12 +194,14 @@ export class BoilerplateDetailsComponent implements OnInit {
result.instance = result.instance?.replace(/ /g, "_") result.instance = result.instance?.replace(/ /g, "_")
} }
if (result.instance) { 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); //console.log(this.addinstance);
this.mainService.setinstances(this.route.snapshot.params.gb, this.addinstance, (result.comment ? result.comment : " ")) this.mainService.setinstances(this.route.snapshot.params.gb, this.addinstance, (result.comment ? result.comment : " "))
.subscribe( .subscribe(
data => { data => {
this.prefchild.getchoices(this.route.snapshot.params.gb);
this.mainchild.getmainchoices(this.route.snapshot.params.gb); this.mainchild.getmainchoices(this.route.snapshot.params.gb);
this.sufchild.getflowchoices(this.route.snapshot.params.gb);
//console.log(data); //console.log(data);
}, },
error => { error => {
...@@ -169,7 +214,7 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -169,7 +214,7 @@ export class BoilerplateDetailsComponent implements OnInit {
value.TheClasses.forEach(function (value) { value.TheClasses.forEach(function (value) {
if (classes == value.Class) { if (classes == value.Class) {
//UI - Add instance of a Class (e.g instance for System : Vehicle) //UI - Add instance of a Class (e.g instance for System : Vehicle)
if (!subclass) { if (!subclass && !subsubclass) {
if (value.Instance_of_Class) { if (value.Instance_of_Class) {
value.Instance_of_Class.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }) value.Instance_of_Class.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
} }
...@@ -179,7 +224,7 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -179,7 +224,7 @@ export class BoilerplateDetailsComponent implements OnInit {
} }
} }
//UI - Add instance of a SubClass (e.g instance for System : Software : Plan) //UI - Add instance of a SubClass (e.g instance for System : Software : Plan)
if (subclass) { if (subclass && !subsubclass) {
if (value.Subclass) { if (value.Subclass) {
value.Subclass.forEach(function (value) { value.Subclass.forEach(function (value) {
if (subclass == value.SubClass_name) { if (subclass == value.SubClass_name) {
...@@ -196,15 +241,101 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -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 : " " }) } } if (!classes) {
else { value.GeneralInstances = []; value.GeneralInstances.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }); } 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))); } } else { this.notifier.notify("warning", (JSON.stringify(error.error.detail))); }
}); });
//this.ngOnInit(); //this.ngOnInit();
...@@ -215,38 +346,38 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -215,38 +346,38 @@ export class BoilerplateDetailsComponent implements OnInit {
}); });
} }
prefixs = [ prefixs = [
{name: 'P1', details: "If/Unless <logical expression>", explanation: 'Expresses a logical condition. Paraphrases: in case, provided that, on condition that.'}, { 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: '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: '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 = [ mains = [
{name: 'M1', details: "system/function shall [not] set [<quantifier>] item [to stateValue]", explanation: 'Sets item Paraphrases: initiate, reset, update.'}, { 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: '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: '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: '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: '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: '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: '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: '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: '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: '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: '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: '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: '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: '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: '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: 'M16', details: "system shall [not] contain system", explanation: 'System decomposition.' },
]; ];
suffixs = [ suffixs = [
{name: 'S1', details: "<numerical-afirmative> j <closed-interval> [per <time-unit>]", explanation: ''}, { name: 'S1', details: "<numerical-afirmative> j <closed-interval> [per <time-unit>]", explanation: '' },
{name: 'S2', details: "after/before flow", 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: '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: 'S4', details: "at the beginning/at the end", explanation: '' },
{name: 'S5', details: "at even intervals", explanation: ''}, { name: 'S5', details: "at even intervals", explanation: '' },
{name: 'S6', details: "sequentially", 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 @@ ...@@ -46,8 +46,8 @@
<!-- Name Column --> <!-- Name Column -->
<ng-container matColumnDef="title_data"> <ng-container matColumnDef="title_data">
<th mat-header-cell *matHeaderCellDef> Title </th> <th mat-header-cell *matHeaderCellDef> Title </th>
<td mat-cell *matCellDef="let element" matTooltip={{get_metrics(element.title_data)}} > {{element.title_data}} <span <td mat-cell *matCellDef="let element" matTooltip={{get_metrics(element.title_data)}}> {{element.title_data}}
*ngIf="get_metrics(element.title_data).length > 0" matBadge={{get_metrics(element.title_data).length}} <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> matBadgeColor="warn" matBadgeSize="small" position="above"> &nbsp;&nbsp; </span>
</td> </td>
</ng-container> </ng-container>
......
...@@ -156,19 +156,21 @@ export class BoilerplateListComponent implements OnInit { ...@@ -156,19 +156,21 @@ export class BoilerplateListComponent implements OnInit {
this.boilerplateService.getAllInfer(this.route.snapshot.params.gb) this.boilerplateService.getAllInfer(this.route.snapshot.params.gb)
.subscribe( .subscribe(
data => { data => {
console.log(data);
this.currentInfer = data[0]; this.currentInfer = data[0];
this.infer = data; this.infer = data;
const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\"")) if (data[0]) {
var final = [] const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
for (let i of this.list_of_inference_metrics) { var final = []
if (obj[i] != undefined) { 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 = [{ this.chartOption.series = [{
type: 'pie', type: 'pie',
radius: ['40%', '70%'], radius: ['40%', '70%'],
......
<div fxLayoutAlign="end"> <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>
<div class="form-row"> <div class="form-row">
<div class="col"> <div class="col">
...@@ -91,9 +91,10 @@ ...@@ -91,9 +91,10 @@
<mat-label>Quantifier</mat-label> <mat-label>Quantifier</mat-label>
<input placeholder="Pick one" aria-label="Number" matInput [formControl]="quantifierControl" type="text" <input placeholder="Pick one" aria-label="Number" matInput [formControl]="quantifierControl" type="text"
[matAutocomplete]="autoquantifier"> [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"> <mat-option *ngFor="let option of quantifierfilteredOptions | async" [value]="option">
{{option}} {{option.split(" : ").pop()}}
</mat-option> </mat-option>
</mat-autocomplete> </mat-autocomplete>
</mat-form-field> </mat-form-field>
...@@ -116,9 +117,10 @@ ...@@ -116,9 +117,10 @@
<mat-label>Number Unit</mat-label> <mat-label>Number Unit</mat-label>
<input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="numunitControl" <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="numunitControl"
[matAutocomplete]="autonumunit"> [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"> <mat-option *ngFor="let option of numunitfilteredOptions | async" [value]="option">
{{option}} {{option.split(" : ").pop()}}
</mat-option> </mat-option>
</mat-autocomplete> </mat-autocomplete>
</mat-form-field> </mat-form-field>
......
<div class="form-row"> <div class="form-row">
<div class="col"> <div class="col">
<form class="form-group form-inline" ngNativeValidate> <form class="form-group form-inline" ngNativeValidate>
<mat-form-field class="example-full-width"> <mat-form-field class="example-full-width">
<mat-label>Suffix</mat-label> <mat-label *ngIf="this.suffixControl.value !=null">Suffix :{{this.suffixControl.value.slice(0,
<input type="text" this.suffixControl.value.indexOf(':'))}}</mat-label>
placeholder="Pick one" <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="suffixControl" required
aria-label="Number" [matAutocomplete]="autosuffix">
matInput <mat-autocomplete autoActiveFirstOption #autosuffix="matAutocomplete" showPanel="true"
[formControl]="suffixControl" [displayWith]="displayFn">
required <mat-option *ngFor="let option of suffixfilteredOptions | async" [value]="option">
[matAutocomplete]="autosuffix" {{option.split(" : ").pop()}}
> </mat-option>
<mat-autocomplete autoActiveFirstOption #autosuffix="matAutocomplete"> </mat-autocomplete>
<mat-option *ngFor="let option of suffixfilteredOptions | async" [value]="option"> </mat-form-field>
{{option}} </form>
</mat-option> </div>
</mat-autocomplete> <div class="col">
</mat-form-field> <form class="form-group form-inline">
</form> <mat-form-field class="example-full-width">
</div> <mat-label>Numerical Value</mat-label>
<div class="col" > <input type="text" matInput [(ngModel)]="currentsuffix.numerical" name="numerical">
<form class="form-group form-inline"> </mat-form-field>
<mat-form-field class="example-full-width"> </form>
<mat-label>Numerical Value</mat-label> </div>
<input type="text" matInput [(ngModel)]="currentsuffix.numerical" name="numerical"> <div class="col">
</mat-form-field> <form class="form-group form-inline">
</form> <mat-form-field class="example-full-width">
</div> <mat-label *ngIf="this.mumerical_unitsControl.value !=null">Numerical Value
<div class="col"> : {{this.mumerical_unitsControl.value.slice(0,
<form class="form-group form-inline"> this.mumerical_unitsControl.value.indexOf(':'))}}</mat-label>
<mat-form-field class="example-full-width"> <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="mumerical_unitsControl"
<mat-label>Unit</mat-label> [matAutocomplete]="autonumsuffix">
<input type="text" <mat-autocomplete autoActiveFirstOption #autonumsuffix="matAutocomplete" showPanel="true"
placeholder="Pick one" [displayWith]="displayFn">
aria-label="Number" <mat-option *ngFor="let option of mumerical_unitsfilteredOptions | async" [value]="option">
matInput {{option.split(" : ").pop()}}
[formControl]="mumerical_unitsControl" </mat-option>
[matAutocomplete]="automumerical_units" </mat-autocomplete>
> </mat-form-field>
<mat-autocomplete autoActiveFirstOption #automumerical_units="matAutocomplete"> </form>
<mat-option *ngFor="let option of mumerical_unitsfilteredOptions | async" [value]="option"> </div>
{{option}} <div class="col" *ngIf="this.mumerical_unitsControl.value !=null">
</mat-option> <form class="form-group form-inline"
</mat-autocomplete> [ngStyle]=" showflow(this.suffixControl.value) ? {'visibility': 'visible'} : {'visibility': 'hidden'}">
</mat-form-field> <mat-form-field class="example-full-width">
</form> <mat-label *ngIf="flowControl.value !=null">Flow or Function : {{flowControl.value.slice(0,
</div> flowControl.value.indexOf(':'))}}</mat-label>
<div class="col"> <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="flowControl" required
<form class="form-group form-inline"> [matAutocomplete]="autoflow">
<mat-form-field class="example-full-width"> <mat-autocomplete autoActiveFirstOption #autoflow="matAutocomplete" showPanel="true" [displayWith]="displayFn">
<mat-label *ngIf="flowControl.value !=null">Flow : {{flowControl.value.slice(0, flowControl.value.indexOf(':'))}}</mat-label> <mat-option *ngFor="let option of flowfilteredOptions | async" [value]="option">
<mat-label>Flow</mat-label> {{option.split(" : ").pop()}}
<input type="text" </mat-option>
placeholder="Pick one" </mat-autocomplete>
aria-label="Number" </mat-form-field>
matInput </form>
[formControl]="flowControl" </div>
[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> </div>
\ No newline at end of file
...@@ -26,6 +26,7 @@ export class SuffixDetailsComponent implements OnInit { ...@@ -26,6 +26,7 @@ export class SuffixDetailsComponent implements OnInit {
flowControl = new FormControl(); flowControl = new FormControl();
flow: string[] = []; flow: string[] = [];
flowfilteredOptions: Observable<string[]>; flowfilteredOptions: Observable<string[]>;
flowControlisDivVisible = false
public static id: any[] = []; public static id: any[] = [];
private readonly notifier: NotifierService; private readonly notifier: NotifierService;
...@@ -61,7 +62,10 @@ export class SuffixDetailsComponent implements OnInit { ...@@ -61,7 +62,10 @@ export class SuffixDetailsComponent implements OnInit {
} }
ngOnInit(): void { 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); this.getAllSuffix(this.route.snapshot.params.id);
} }
...@@ -75,6 +79,16 @@ export class SuffixDetailsComponent implements OnInit { ...@@ -75,6 +79,16 @@ export class SuffixDetailsComponent implements OnInit {
return ""; 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[] { private _filter(data: string[], value: string): string[] {
const filterValue = value.toLowerCase(); const filterValue = value.toLowerCase();
return data.filter(option => option.toLowerCase().includes(filterValue)); return data.filter(option => option.toLowerCase().includes(filterValue));
...@@ -119,7 +133,7 @@ export class SuffixDetailsComponent implements OnInit { ...@@ -119,7 +133,7 @@ export class SuffixDetailsComponent implements OnInit {
updateSuffix(): void { updateSuffix(): void {
this.currentsuffix.s_choices = this.suffixControl.value; this.currentsuffix.s_choices = this.suffixControl.value;
this.currentsuffix.mumerical_units = this.mumerical_unitsControl.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++) { for (let i = 0; i < SuffixDetailsComponent.id.length; i++) {
this.suffixService.update(this.route.snapshot.params.id, SuffixDetailsComponent.id[i], this.currentsuffix) this.suffixService.update(this.route.snapshot.params.id, SuffixDetailsComponent.id[i], this.currentsuffix)
.subscribe( .subscribe(
...@@ -133,32 +147,50 @@ export class SuffixDetailsComponent implements OnInit { ...@@ -133,32 +147,50 @@ export class SuffixDetailsComponent implements OnInit {
} }
getchoices(): void { getflowchoices(prefix_group: any): void {
this.suffixService.getsuffix() this.suffixService.getsuffixflow(prefix_group)
.subscribe( .subscribe(
data => { data => {
for (let x = 0; x < data.length; x++) { //set flow choices
if (this.suffix.indexOf(data[x][1]) == -1) { this.setflow(JSON.parse(data[0].flow_choices));
this.suffix.push(data[x][1]); 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 => { error => {
console.log(error); console.log(error);
}); });
this.suffixService.getnumunits() }
.subscribe( setflow(strIntoObj: any): void {
data => { for (let x = 0; x < strIntoObj.length; x++) {
for (let x = 0; x < data.length; x++) { if (this.flow.indexOf(strIntoObj[x][1]) == -1) {
if (this.mumerical_units.indexOf(data[x][1]) == -1) { this.flow.push((strIntoObj[x][1]));
this.mumerical_units.push(data[x][1]); }
} }
} }
},
error => { setsuffix(strIntoObj: any): void {
console.log(error); for (let x = 0; x < strIntoObj.length; x++) {
}); if (this.suffix.indexOf(strIntoObj[x][1]) == -1) {
this.suffixService.getflow() 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( .subscribe(
data => { data => {
for (let x = 0; x < data.length; x++) { for (let x = 0; x < data.length; x++) {
...@@ -169,8 +201,4 @@ export class SuffixDetailsComponent implements OnInit { ...@@ -169,8 +201,4 @@ export class SuffixDetailsComponent implements OnInit {
}, },
error => { error => {
console.log(error); console.log(error);
}); });*/
\ No newline at end of file
}
}
...@@ -45,6 +45,27 @@ export class SubClasses { ...@@ -45,6 +45,27 @@ export class SubClasses {
SubClass_name?: any; SubClass_name?: any;
SubclassComment?: any SubclassComment?: any
InstanceOfSubclass?: Instances[]; 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 { export class Instances {
......
...@@ -6,6 +6,7 @@ import { environment } from '../../environments/environment'; ...@@ -6,6 +6,7 @@ import { environment } from '../../environments/environment';
const baseUrl = environment.apiroot + 'api-auth/groupboilerplates/0/boilerplates/'; const baseUrl = environment.apiroot + 'api-auth/groupboilerplates/0/boilerplates/';
const Url = '/suffix/'; const Url = '/suffix/';
const baseUrl2 = environment.apiroot + 'api-auth/groupboilerplates/';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
...@@ -45,5 +46,9 @@ export class SuffixService { ...@@ -45,5 +46,9 @@ export class SuffixService {
getflow(): Observable<any> { getflow(): Observable<any> {
return this.http.get(environment.apiroot +`api-auth/suffix/choices/flow/`); 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"), ...@@ -45,11 +45,17 @@ MAIN_CHOICES = ( ("",""), ("M1", "M1"),
#FUNCTION_INSTANCES_COMMENTS = get_dmo_instance_and_comment("SAO#Function") #FUNCTION_INSTANCES_COMMENTS = get_dmo_instance_and_comment("SAO#Function")
# #
SHALL_CHOICES = ( ("shall", "shall"), ("shall not", "shall not")) SHALL_CHOICES = ( ("shall", "shall"), ("shall not", "shall not"))
QUANTIFIER_CHOICES = ( ("None","None"), ("All", "All"), ("Only", "Only"), #QUANTIFIER_CHOICES = ( ("None","None"), ("All", "All"), ("Only", "Only"),
("More Than", "More Than"), ("Less Than", "Less Than"), ("Exactly","Exactly"), # ("More Than", "More Than"), ("Less Than", "Less Than"), ("Exactly","Exactly"),
("At Least", "At Least"), ("At Most", "At Most") # ("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")) #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
#ITEM_CHOICES = get_instances("SAO#Item") #ITEM_CHOICES = get_instances("SAO#Item")
#ITEM_CLASSES_COMMENTS = get_dmo_classes_and_comment("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^ ...@@ -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_instances("LO#Verb")
VERB_CHOICES = get_verb_file_and_instances("LO#Verb") VERB_CHOICES = get_verb_file_and_instances("LO#Verb")
#test to add M #test to add M
CLASS_CHOICES = (("SYSTEM","SYSTEM"), ("FUNCTION","FUNCTION"), ("SHALL","SHALL/SHALL NOT"), CLASS_CHOICES = (("SYSTEM","SYSTEM"), ("FUNCTION","FUNCTION"), ("SHALL","SHALL/SHALL NOT"),
("QUANTIFIER","QUANTIFIER"), ("NUMBER_UNITS","NUMBER_UNITS"), ("ITEM","ITEM"), ("QUANTIFIER","QUANTIFIER"), ("NUMBER_UNITS","NUMBER_UNITS"), ("ITEM","ITEM"),
......
...@@ -36,6 +36,9 @@ LOGICAL_EXPRESSION = ( ("",""), ...@@ -36,6 +36,9 @@ LOGICAL_EXPRESSION = ( ("",""),
#Need fixing #Need fixing
#VERB_CHOICES_PREFIX = ( ("","")) #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 #Must read this info from the Ontology
...@@ -106,15 +109,19 @@ def update_instances(instance): ...@@ -106,15 +109,19 @@ def update_instances(instance):
g.load(instance.ontology_file, format="turtle") g.load(instance.ontology_file, format="turtle")
#PREFIX_SYNTAX = get_prefix_syntax(g) #PREFIX_SYNTAX = get_prefix_syntax(g)
VERB_CHOICES_PREFIX = get_prefix_verbs(g) VERB_CHOICES_PREFIX = get_prefix_verbs(g)
SYSTEM_CHOICES = get_instances_g("SAO#System",g) SYSTEM_CHOICES = get_instances_g("SAO#System",g, list_of_DSO)
FUNCTION_CHOICES = get_instances_g("SAO#Function",g) FUNCTION_CHOICES = get_instances_g("SAO#Function",g, list_of_DSO)
ITEM_CHOICES = get_instances_g("SAO#Item",g) ITEM_CHOICES = get_instances_g("SAO#Item",g, list_of_DSO)
INTERFACE_CHOICES = get_instances_g("SAO#Interface",g) INTERFACE_CHOICES = get_instances_g("SAO#Interface",g, list_of_DSO)
CONNECTION_CHOICES = get_instances_g("SAO#Connection",g) CONNECTION_CHOICES = get_instances_g("SAO#Connection",g, list_of_DSO)
FLOW_CHOICES = get_instances_g("SAO#Flow",g) FLOW_CHOICES = get_instances_g("SAO#Flow",g, list_of_DSO)
STATE_CHOICES = get_instances_g("SAO#State",g) STATE_CHOICES = get_instances_g("SAO#State",g, list_of_DSO)
STATE_SET_CHOICES = get_instances_g("SAO#StateSet",g) STATE_SET_CHOICES = get_instances_g("SAO#StateSet",g, list_of_DSO)
STATE_VALUE_CHOICES =get_instances_g("SAO#StateValue",g) 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( 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), 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), 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 ...@@ -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"), NUMERICAL_AFFIRMATIVE_CHOICES = (("MORE THAN", "MORE THAN"), ("LESS THAN", "LESS THAN"), ("EXACTLY","EXACTLY"),
("AT LEAST", "AT LEAST"), ("AT MOST", "AT MOST")) ("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_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") #TIME_UNITS_CHOICES = (("SECONDS","SECONDS"), ("MINUTES","MINUTES"), ("MILLISECONDS","MILLISECONDS"), ("CYCLES","CYCLES"))
#FLOW_CHOICES = get_instances("SAO#Flow")
# FLOW returns () # FLOW returns ()
S2_CHOICES = (("BEFORE","BEFORE"), ("AFTER","AFTER")) 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")) 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")) 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"))
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): def create_suffix(instance):
...@@ -49,13 +59,16 @@ class Suffix(models.Model): ...@@ -49,13 +59,16 @@ class Suffix(models.Model):
boilerplate_of_suffix = models.ForeignKey('reqtool.Boilerplate', related_name='suffix_boilerplate', on_delete=models.CASCADE) 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) suffix_owner = models.ForeignKey(User, related_name='suffix_owner', on_delete=models.CASCADE)
#prefix templates #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 #if S1
numerical = models.CharField(blank=True, null=True, max_length=10) 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) #time_units = models.CharField(choices=TIME_UNITS_CHOICES, max_length=100, blank=True)
#if S2/S3 #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 #find suffix
suffix_choices = models.CharField(choices=SUFFIX_CHOICES, max_length=100, blank=True) suffix_choices = models.CharField(choices=SUFFIX_CHOICES, max_length=100, blank=True)
#custom suffix #custom suffix
......
import os, subprocess, shutil import os, subprocess, shutil
from rdflib import Graph, BNode from rdflib import XSD, Graph, BNode
from rdflib.namespace import RDFS 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 * from reqman.apps.reqtool.rest_api.services.parse_ontologies import *
#HERE #HERE
...@@ -11,9 +11,12 @@ Ontology_file = "../../Ontologies/2022_AOCS.ttl" ...@@ -11,9 +11,12 @@ Ontology_file = "../../Ontologies/2022_AOCS.ttl"
list_of_inference_metrics = ["IncompleteRequirement", "AmbiguousRequirement", list_of_inference_metrics = ["IncompleteRequirement", "AmbiguousRequirement",
"InconsistentRequirement","NoisyRequirement","OpaqueRequirement","RedundantRequirement"] "InconsistentRequirement","NoisyRequirement","OpaqueRequirement","RedundantRequirement"]
info_metric = ["isMissingConcept", "isMissingInstanceOf", "isMissingProducer", "isMissingState", "hasAmbiguousConcept", "hasAmbiguousConcept2",
"hasNoisyConcept", "hasOpaqueConcept", "isInconsistentTo"]
prefix_syntax = get_prefix_syntax(g) prefix_syntax = get_prefix_syntax(g)
main_syntax = get_main_sytax_inference() main_syntax = get_main_sytax_inference(g)
def getclassofprefix(prefix): def getclassofprefix(prefix):
return(findclassofprefix(prefix)) return(findclassofprefix(prefix))
...@@ -79,7 +82,7 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix): ...@@ -79,7 +82,7 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
g.load('../../Ontologies/'+ontfile, format="turtle") g.load('../../Ontologies/'+ontfile, format="turtle")
else : else :
g.load(ontfile, format="turtle") g.load(ontfile, format="turtle")
#print(ontfile) print(ontfile)
#remove the requirements from the RDO-instances #remove the requirements from the RDO-instances
previous_req = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO-instances#") previous_req = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO-instances#")
g.remove((previous_req, None, None)) g.remove((previous_req, None, None))
...@@ -88,27 +91,31 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix): ...@@ -88,27 +91,31 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
g.add((per_instances + title, RDF.type, rdo + 'Requirement')) g.add((per_instances + title, RDF.type, rdo + 'Requirement'))
try: try:
if (boilerplate[i][0]['has_prefix'] == True): #If the requirement has Prefix 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, 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'])) 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(" : ") 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+(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), RDF.type, (per_instances+("SystemStateValueContraint"))))
g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToState", lo + prefix_attr_splitter[1].strip())) g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToState", rbo + prefix_verb_splitter[len(prefix_verb_splitter)-1].strip()))
for j in prefixmodel: g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToSystem", rbo + prefixsub_splitter[len(prefixsub_splitter)-1].strip()))
if prefix[i][0][j] != "": g.add((per_instances+("SystemStateValueContraint_"+title), rbo+"isRelatedToStateValue", rbo + prefix_attr_splitter[len(prefix_attr_splitter)-1].strip()))
sub_instance_file, prefix_subject_splitter = getinstancefile(prefix[i][0][j], g) elif(prefix_attr_splitter[0]=="StateValue"):
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+(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: 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+(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), 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())) g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToAction", lo + prefix_verb_splitter[len(prefix_verb_splitter)-1].strip()))
for j in prefixmodel: g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToStimulus", rbo + prefixsub_splitter[len(prefixsub_splitter)-1].strip()))
if prefix[i][0][j] != "": if(prefix_attr_splitter[0]=='Item'):
sub_instance_file, prefix_subject_splitter = getinstancefile(prefix[i][0][j], g) g.add((per_instances+(prefix_verb_splitter[0]+"OccuringFunctionality"+title), rbo+"isRelatedToTraversingConcept", rbo + prefix_attr_splitter[len(prefix_attr_splitter)-1].strip()))
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]))) 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: except:
raise APIException("The instances in Prefix of Boilerplate "+title+" are not exist in the Ontology") raise APIException("The instances in Prefix of Boilerplate "+title+" are not exist in the Ontology")
try: try:
...@@ -125,11 +132,12 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix): ...@@ -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", "state_item_before_verb", "statevalue_before_verb", "statevalue_system_connection_stateset"]
mainmodel=["flow_function_interface_item_system_state_stateset", "statevalue_system_connection_stateset"] mainmodel=["flow_function_interface_item_system_state_stateset", "statevalue_system_connection_stateset"]
for j in mainmodel: for j in mainmodel:
if ( main[i][0]['main_choices'] == 'M10'): if(main[i][0][j] != ""):
instance_file, splitter_1 = getinstancefile(main[i][0][j], g) 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]))) if ( splitter_1[0] =='Item' or splitter_1[0] =='Flow' ):
elif main[i][0][j] != "": print(main[i][0][j])
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])))
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]))) 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"] mainbeforeverbmodel=["state_item_before_verb", "statevalue_before_verb"]
for j in mainbeforeverbmodel: for j in mainbeforeverbmodel:
...@@ -137,30 +145,99 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix): ...@@ -137,30 +145,99 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
instance_file, splitter_1 = getinstancefile(main[i][0][j], g) 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]))) 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'] != "": 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(" ", ""))))) quantimain= main[i][0]['quantifier'].split(':')
per = URIRef('http://delab.csd.auth.gr/ontologies/2018/LO#'+ (main[i][0]['quantifier']).replace(" ", "")) if(quantimain[len(quantimain)-2].strip() == "NonNumericalAffirmative"):
quant = URIRef(rbo + "Quantifier") # Initial Value if not any g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToQuantifier", lo+ (quantimain[len(quantimain)-1].strip())))
for s, p, o in g.triples((per, RDFS.subClassOf, None)): #subClassOf elif(quantimain[len(quantimain)-2].strip() == "Negative"):
#print(o) g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToQuantifier", lo+ (quantimain[len(quantimain)-1].strip())))
if ('RBO' in o): elif ( quantimain[len(quantimain)-2].strip() == "ClosedInterval"):
quant=o g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToQuantifier", (per_instances+(title+ "_Quantifier" ))))
g.add((per_instances+(title+"_"+ (main[i][0]['quantifier']).replace(" ", "")), RDF.type, quant)) g.add((per_instances+(title+ "_Quantifier" ), RDF.type, rbo+"ClosedInterval"))
g.add((per_instances+(title+"_"+ (main[i][0]['quantifier']).replace(" ", "")), rbo+"hasAdverb", lo + (main[i][0]['quantifier']).replace(" ", ""))) g.add((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToNumericalQuantifier", lo+quantimain[len(quantimain)-1].strip()))
if main[i][0]['numerical'] != "": #isRelatedToNumerical
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((per_instances+(title+ "_Quantifier" ), rbo+"isRelatedToNumerical", per_instances+(title+ "_Quantifier_Numerical")))
g.add((URIRef(per_instances+(main[i][0]['quantifier']).replace(" ", "")+"_"+str(main[i][0]['numerical'])), RDF.type, URIRef(rbo+"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: except:
raise APIException("The instances in MAIN of Boilerplate "+title+" are not exist in the Ontology") raise APIException("The instances in MAIN of Boilerplate "+title+" are not exist in the Ontology")
try: try:
if (boilerplate[i][0]['has_suffix'] == True): if (boilerplate[i][0]['has_suffix'] == True):
g.add((per_instances + title, rdo + 'hasSuffix', per_instances+(title+"_"+ suffix[i][0]['suffix_choices']))) typesuffix = suffix[i][0]['s_choices'].split(':')
#Need S1 numunit=suffix[i][0]["mumerical_units"].split(":")
#Need S2 flowsuf=suffix[i][0]['flow'].split(':')
#Need S3 if(suffix[i][0]['s_choices']!= ""):
g.add((per_instances+(title+"_"+ suffix[i][0]['suffix_choices']), RDF.type, URIRef(rbo+ suffix[i][0]['suffix_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: except:
raise APIException("The instances in SUFFIX of Boilerplate "+title+" are not exist in the Ontology") raise APIException("The instances in SUFFIX of Boilerplate "+title+" are not exist in the Ontology")
#g.remove((per_instances + title, None, None))
try : try :
g.serialize(destination=ontfile+'.ttl', format='turtle') g.serialize(destination=ontfile+'.ttl', format='turtle')
return (ontfile) return (ontfile)
...@@ -193,7 +270,19 @@ def shacl(ontotlogy_file): ...@@ -193,7 +270,19 @@ def shacl(ontotlogy_file):
#metrics_dict["IncompleteRequirement"] = [s] #metrics_dict["IncompleteRequirement"] = [s]
get_title = str(s).split("#") get_title = str(s).split("#")
metrics_dict[inf_metr].append(get_title[1]) 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) return(metrics_dict)
...@@ -210,14 +299,13 @@ def findclassofprefix(listofprefix): ...@@ -210,14 +299,13 @@ def findclassofprefix(listofprefix):
if (currentstate[0] == "State"): if (currentstate[0] == "State"):
if (currentsubjectspl[0] != "System"): if (currentsubjectspl[0] != "System"):
raise APIException("The Subject must be a System") raise APIException("The Subject must be a System")
print(currentverb)
if (currentverb[1] == "is"): if (currentverb[1] == "is"):
if (currentsubjectspl[0] == "System"): if (currentsubjectspl[0] == "System"):
raise APIException("The Subject must be an Item") raise APIException("The Subject must be an Item")
# #
for prefix in prefix_syntax: for prefix in prefix_syntax:
for inprefix in prefix_syntax[prefix]: 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 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 currentattr.split(":")[0].strip() in prefix_syntax[prefix][inprefix.split("_")[0]+"_Attribute"]:
if listofprefix['prefix'] == "If": if listofprefix['prefix'] == "If":
...@@ -255,20 +343,20 @@ def findclassofmain(listofmain): ...@@ -255,20 +343,20 @@ def findclassofmain(listofmain):
if (currenSubStateValue[0] != 'StateValue'): if (currenSubStateValue[0] != 'StateValue'):
classlist.append("ERROR") classlist.append("ERROR")
return classlist return classlist
if (currenLast[0] == 'StateSet'): if (currenLast[0].strip() == 'StateSet'):
if(currentattr[0] != 'State'): if(currentattr[0].strip() != 'State'):
classlist.append("ERROR") classlist.append("ERROR")
return classlist return classlist
if (currenLast[0] == 'Connection'): if (currenLast[0].strip() == 'Connection'):
if(currentattr[0] != 'System'): if(currentattr[0].strip() != 'System'):
classlist.append("ERROR") classlist.append("ERROR")
return classlist return classlist
if (currenLast[0] == 'StateValue'): if (currenLast[0].strip() == 'StateValue'):
if(currentattr[0] != 'Item'): if(currentattr[0].strip() != 'Item' and currentattr[0].strip() != 'State'):
classlist.append("ERROR") classlist.append("ERROR")
return classlist return classlist
if (currenLast[0] == 'System'): if (currenLast[0].strip() == 'System'):
if(currentattr[0] != 'Interface'): if(currentattr[0].strip() != 'Interface'):
classlist.append("ERROR") classlist.append("ERROR")
return classlist return classlist
# #
...@@ -284,5 +372,6 @@ def findclassofmain(listofmain): ...@@ -284,5 +372,6 @@ def findclassofmain(listofmain):
if attrmain == currentattr[0].strip(): if attrmain == currentattr[0].strip():
classlist.append('M'+str(i+1)) classlist.append('M'+str(i+1))
return(classlist) return(classlist)
from rdflib import Graph, BNode from rdflib import Graph, BNode
from rdflib.namespace import RDFS 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 #from subprocess import call
...@@ -8,13 +8,16 @@ from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace ...@@ -8,13 +8,16 @@ from rdflib import ConjunctiveGraph, URIRef, RDFS, RDF, Namespace
#Ontology_file = "../../Ontologies/Mokos_18_1_7_47.ttl" #Ontology_file = "../../Ontologies/Mokos_18_1_7_47.ttl"
#Ontology_file = "../../Ontologies/Autonomy_v1.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" subClass_instances = "../../Ontologies/instances_subclass.txt"
#HERE #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-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-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"] #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#"] DSO = ["http://delab.csd.auth.gr/ontologies/2018/DSO#"]
...@@ -132,7 +135,7 @@ info_dict = {} ...@@ -132,7 +135,7 @@ info_dict = {}
'''Get Instaces - return tuple''' '''Get Instaces - return tuple'''
def get_instances_g(keyword, g): def get_instances_g(keyword, g, list_of_DSO):
#get_file_and_instances(keyword) #get_file_and_instances(keyword)
keywordspl = keyword.split("#") keywordspl = keyword.split("#")
in_list = [keywordspl[len(keywordspl)-1]] in_list = [keywordspl[len(keywordspl)-1]]
...@@ -147,6 +150,7 @@ def get_instances_g(keyword, g): ...@@ -147,6 +150,7 @@ def get_instances_g(keyword, g):
for uri in list_of_DSO: for uri in list_of_DSO:
per = URIRef(uri +extra) per = URIRef(uri +extra)
for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
#print('res',s)
spl = s.split("#") spl = s.split("#")
in_list.append(spl[len(spl) - 1]) in_list.append(spl[len(spl) - 1])
for extra in in_list: for extra in in_list:
...@@ -177,6 +181,7 @@ def get_file_and_instances(keyword, g): ...@@ -177,6 +181,7 @@ def get_file_and_instances(keyword, g):
for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf for s, p, o in g.triples((None, RDFS.subClassOf, per)): #subClassOf
spl = s.split("#") spl = s.split("#")
in_list.append(spl[len(spl) - 1]) in_list.append(spl[len(spl) - 1])
#print(in_list)
#find two layer down System: Subclass : Instance #find two layer down System: Subclass : Instance
for extra in in_list: for extra in in_list:
for uri in list_of_DSO: for uri in list_of_DSO:
...@@ -286,7 +291,6 @@ def get_dmo_classes_and_comment(keyword, g): ...@@ -286,7 +291,6 @@ def get_dmo_classes_and_comment(keyword, g):
comment_class = (str(o).replace("\r","")).replace("\n","") comment_class = (str(o).replace("\r","")).replace("\n","")
suclass_dict = {} suclass_dict = {}
subclass_list = [] subclass_list = []
sub_ins_dict = {}
for uri in list_of_DSO: for uri in list_of_DSO:
subclas_name = "" subclas_name = ""
per2 = URIRef(uri +comment) per2 = URIRef(uri +comment)
...@@ -309,13 +313,103 @@ def get_dmo_classes_and_comment(keyword, g): ...@@ -309,13 +313,103 @@ def get_dmo_classes_and_comment(keyword, g):
for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)): for q1, w1, m1 in g.triples((kop2, RDFS.comment, None)):
find_comment_instance = (str(m1).replace("\r","")).replace("\n","") find_comment_instance = (str(m1).replace("\r","")).replace("\n","")
sub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": find_comment_instance} sub_ins_dict = {"Instance": spl2[len(spl2) - 1], "Comment": find_comment_instance}
sub_ins.append(sub_ins_dict) sub_ins.append(sub_ins_dict)
suclass_dict = {'SubClass_name': subclas_name, 'SubclassComment':find_comment, 'InstanceOfSubclass': sub_ins} ###############################
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) subclass_list.append(suclass_dict)
############################################
dmo_dic = {"Class": name_class, "Comment":comment_class, 'Subclass': subclass_list, 'Instance_of_Class':instance_list} dmo_dic = {"Class": name_class, "Comment":comment_class, 'Subclass': subclass_list, 'Instance_of_Class':instance_list}
dic_list.append(dmo_dic) dic_list.append(dmo_dic)
if out_list_com: if out_list_com:
Dictionary_Data = { "Name":section, "TheClasses" : dic_list, "GeneralInstances": dic_list_in} Dictionary_Data = { "Name":section, "TheClasses" : dic_list, "GeneralInstances": dic_list_in}
#print(Dictionary_Data)
return Dictionary_Data return Dictionary_Data
#return dic_list #return dic_list
else: else:
...@@ -330,6 +424,10 @@ def get_dmo_classes_and_comment(keyword, g): ...@@ -330,6 +424,10 @@ def get_dmo_classes_and_comment(keyword, g):
return Dictionary_Data return Dictionary_Data
#return dic_list_backup #return dic_list_backup
#Classes of classes and Comments #Classes of classes and Comments
def get_dmo_classes_of_classes_and_comment(keyword): def get_dmo_classes_of_classes_and_comment(keyword):
dmo_dic = {} dmo_dic = {}
...@@ -447,24 +545,18 @@ def check_quantifier(bnodes_uriref): ...@@ -447,24 +545,18 @@ def check_quantifier(bnodes_uriref):
'''Find Boilerplate Attribute - return list''' '''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 = [] bnodes = []
attribute_list = [] attribute_list = []
bnodes_uriref = [str(i) for i in bnodes_uriref] bnodes_uriref = [str(i) for i in bnodes_uriref]
#print(main, bnodes_uriref)
for attribute in bnodes_uriref: for attribute in bnodes_uriref:
if "isRelatedToSubject" in attribute: #if "isRelatedToSubject" in attribute:
pass # pass
elif "isRelatedTo" in attribute: if "isRelatedTo" in attribute:
tmp = attribute.split("#") attribute_list.append(attribute)
if tmp[1] != '': #print(main, attribute_list)
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])
attribute_list = list(filter(("Action").__ne__, attribute_list)) attribute_list = list(filter(("Action").__ne__, attribute_list))
attribute_list = list(filter(("Attribute").__ne__, attribute_list)) attribute_list = list(filter(("Attribute").__ne__, attribute_list))
attribute_list = list(filter(("Quantity").__ne__, attribute_list)) attribute_list = list(filter(("Quantity").__ne__, attribute_list))
...@@ -475,6 +567,7 @@ def get_attribute(bnodes_uriref, subjects, related_subjects, verbs): ...@@ -475,6 +567,7 @@ def get_attribute(bnodes_uriref, subjects, related_subjects, verbs):
attribute_list = list(filter(("TraversingConcept").__ne__, attribute_list)) attribute_list = list(filter(("TraversingConcept").__ne__, attribute_list))
tmp_list = [] tmp_list = []
#print(bnodes_uriref)
for i in bnodes_uriref: for i in bnodes_uriref:
if not "isRelatedTo" in i: if not "isRelatedTo" in i:
if not "isRelatedto" in i: if not "isRelatedto" in i:
...@@ -503,40 +596,74 @@ def get_attribute(bnodes_uriref, subjects, related_subjects, verbs): ...@@ -503,40 +596,74 @@ def get_attribute(bnodes_uriref, subjects, related_subjects, verbs):
'''Find Main syntax - return a dict with the syntax''' '''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") get_main = get_instances_list("RBO#Main")
main_dict = {} main_dict = {}
for main in get_main: 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 = [] bnodes = []
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main) p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main)
for s, p, o in g.triples((p, None, None)): for s, p, o in g.triples((p, None, None)):
if isinstance(o, BNode): if isinstance(o, BNode):
bnodes.append(o) bnodes.append(o)
bnodes.sort() data = []
for o1, p1, s1 in g.triples((o, None, None)):
for bn in bnodes: if isinstance(s1, URIRef):
for objects in g.objects(subject=BNode(bn)): data.append(str(s1))
if isinstance(objects, BNode): if isinstance(s1, BNode):
bnodes.append(objects) for objects1 in g.objects(subject=BNode(s1)):
if isinstance(objects1, BNode):
bnodes.sort() for objects2 in g.objects(subject=BNode(objects1)):
if isinstance(objects2, URIRef):
bnodes_uriref = [] data.append(str(objects2))
elif isinstance(objects2, BNode):
for bn in bnodes: for objects3 in g.objects(subject=BNode(objects2)):
for objects in g.objects(subject=BNode(bn)): if isinstance(objects3, URIRef):
if isinstance(objects, URIRef): if(not 'nil' in str(objects3)):
bnodes_uriref.append(objects) data.append(str(objects3))
#tmp_list = list(filter(("nil").__ne__, tmp_list)) strings_with_substring_subState = [string for string in data if "isRelatedToSubjectState" in string]
if(len(strings_with_substring_subState) > 0):
main_dict[main] = {} tmp_list = [string for string in data if string not in strings_with_substring_subState]
main_dict[main]["Subject"] = get_subjects(bnodes_uriref) for i in tmp_list:
main_dict[main]["Related_to_Subject"] = get_related_to_subject(bnodes_uriref) i=i.split('#')
main_dict[main]["Verbs"] = get_verb(bnodes_uriref) main_dict[main]["Related_to_Subject"].append(i[1])
main_dict[main]["Quantifier"] = check_quantifier(bnodes_uriref) strings_with_substring_subItem = [string for string in data if "isRelatedToSubjectItem" in string]
main_dict[main]["Attributes"] = get_attribute(bnodes_uriref, main_dict[main]["Subject"], main_dict[main]["Related_to_Subject"], main_dict[main]["Verbs"]) 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]
#print( main_dict[main]["Subject"]) 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 return main_dict
...@@ -546,36 +673,72 @@ def get_main_sytax(): ...@@ -546,36 +673,72 @@ def get_main_sytax():
main_dict = {} main_dict = {}
main_dict_list = [] main_dict_list = []
for main in get_main: 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 = [] bnodes = []
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main) p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + main)
for s, p, o in g.triples((p, None, None)): for s, p, o in g.triples((p, None, None)):
if isinstance(o, BNode): if isinstance(o, BNode):
bnodes.append(o) bnodes.append(o)
bnodes.sort() data = []
for o1, p1, s1 in g.triples((o, None, None)):
for bn in bnodes: if isinstance(s1, URIRef):
for objects in g.objects(subject=BNode(bn)): data.append(str(s1))
if isinstance(objects, BNode): if isinstance(s1, BNode):
bnodes.append(objects) for objects1 in g.objects(subject=BNode(s1)):
if isinstance(objects1, BNode):
bnodes.sort() for objects2 in g.objects(subject=BNode(objects1)):
if isinstance(objects2, URIRef):
bnodes_uriref = [] data.append(str(objects2))
elif isinstance(objects2, BNode):
for bn in bnodes: for objects3 in g.objects(subject=BNode(objects2)):
for objects in g.objects(subject=BNode(bn)): if isinstance(objects3, URIRef):
if isinstance(objects, URIRef): if(not 'nil' in str(objects3)):
bnodes_uriref.append(objects) data.append(str(objects3))
strings_with_substring_subState = [string for string in data if "isRelatedToSubjectState" in string]
main_dict[main] = {} if(len(strings_with_substring_subState) > 0):
main_dict[main]["Id"] = main tmp_list = [string for string in data if string not in strings_with_substring_subState]
main_dict[main]["Subject"] = get_subjects(bnodes_uriref) for i in tmp_list:
main_dict[main]["Related_to_Subject"] = get_related_to_subject(bnodes_uriref) i=i.split('#')
main_dict[main]["Verbs"] = get_verb(bnodes_uriref) main_dict[main]["Related_to_Subject"].append(i[1])
main_dict[main]["Quantifier"] = check_quantifier(bnodes_uriref) strings_with_substring_subItem = [string for string in data if "isRelatedToSubjectItem" in string]
main_dict[main]["Attributes"] = get_attribute(bnodes_uriref, main_dict[main]["Subject"], main_dict[main]["Related_to_Subject"], main_dict[main]["Verbs"]) if(len(strings_with_substring_subItem) > 0 and len(strings_with_substring_subState)==0):
main_dict_list.append(main_dict[main]) 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 return main_dict_list
...@@ -599,58 +762,65 @@ def get_prefix_syntax(g): ...@@ -599,58 +762,65 @@ def get_prefix_syntax(g):
for i in tmp: for i in tmp:
subclass_data.append(i) subclass_data.append(i)
for pre in subclass_data: for pre in subclass_data:
tmp_list = [] prefix_dict[prefix][str(pre)+"_Verbs"] = []
tmp_list2 = find_triples(pre) prefix_dict[prefix][str(pre)+"_Attribute"] = []
tmp_list2 = [str(i) for i in tmp_list2] prefix_dict[prefix][str(pre)+"_Subject"] = []
for i in tmp_list2: prefix_dict[prefix][str(pre)+"_Quantifier"] = None
tmp = i.split("#") bnodes = []
tmp_list.append(tmp[1]) p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RBO#" + pre)
tmp_list = list(filter(("nil").__ne__, tmp_list)) for s, p, o in g.triples((p, None, None)):
tmp_list = list(filter(("Restriction").__ne__, tmp_list)) if isinstance(o, BNode):
tmp_list = list(filter(("Class").__ne__, tmp_list)) bnodes.append(o)
tmp_list = list(filter(("Action").__ne__, tmp_list)) data = []
tmp_list = list(filter(("Quantity").__ne__, tmp_list)) for o1, p1, s1 in g.triples((o, None, None)):
tmp_list = list(filter(("UnitOfMeasurement").__ne__, tmp_list)) if isinstance(s1, URIRef):
isrelated = [] data.append(str(s1))
sub = [] if( 'syntaxOrder' in p1):
for i in tmp_list: order = int(s1)
if "isRelatedTo" in i: if isinstance(s1, BNode):
isrelated.append(i) for objects1 in g.objects(subject=BNode(s1)):
else: if isinstance(objects1, BNode):
sub.append(i) for objects2 in g.objects(subject=BNode(objects1)):
if len(sub)>1 : if isinstance(objects2, URIRef):
prefix_dict[prefix][str(pre)+"_Verbs"] = [] data.append(str(objects2))
prefix_dict[prefix][str(pre)+"_Attribute"] = [] elif isinstance(objects2, BNode):
prefix_dict[prefix][str(pre)+"_Subject"] = [] for objects3 in g.objects(subject=BNode(objects2)):
# if pre is StateValueConstraint we know that Atribute is StateValue if isinstance(objects3, URIRef):
if "StateValue" in str(pre) and len(sub)>1: if(not 'nil' in str(objects3)):
prefix_dict[prefix][str(pre)+"_Attribute"].append("StateValue") data.append(str(objects3))
sub.remove("StateValue") strings_with_substring_subState = [string for string in data if "isRelatedToStimulus" in string]
else: if( (len(strings_with_substring_subState) > 0) and order == 0):
for i in sub: tmp_list = [string for string in data if string not in strings_with_substring_subState]
for j in isrelated: for i in tmp_list:
if i in j: i=i.split('#')
if i not in prefix_dict[prefix][str(pre)+"_Attribute"]: prefix_dict[prefix][str(pre)+"_Subject"].append(i[1])
prefix_dict[prefix][str(pre)+"_Attribute"].append(i) strings_with_substring_verb = [string for string in data if "isRelatedToAction" in string]
sub.remove(i) if(len(strings_with_substring_verb) > 0 ):
#add verbs tmp_list = [string for string in data if string not in strings_with_substring_verb]
if tmp_list2: for i in tmp_list:
ver = get_verb(tmp_list2) for s, p, o in g.triples((None, RDF.type, URIRef(i))):
if (len(ver)==0): spl = s.split("#")
prefix_dict[prefix][str(pre)+"_Verbs"].append('is') prefix_dict[prefix][str(pre)+"_Verbs"].append(spl[1])
else: strings_with_substring_state = [string for string in data if "isRelatedToState" in string]
prefix_dict[prefix][str(pre)+"_Verbs"].extend(ver) if(len(strings_with_substring_state) > 0 ):
for j in tmp_list2: tmp_list = [string for string in data if string not in strings_with_substring_state]
if "LO" in str(j): for i in tmp_list:
sub.remove(j.split("#")[1]) i = i.split("#")
#Subjects are everything that is not a verb or an attribute - may some erros here prefix_dict[prefix][str(pre)+"_Verbs"].append(i[1])
for newsub in sub: strings_with_substring_quan = [string for string in data if "isRelatedToQuantifier" in string]
if newsub not in prefix_dict[prefix][str(pre)+"_Subject"]: if(len(strings_with_substring_quan) > 0):
if (len(prefix_dict[prefix][str(pre)+"_Attribute"]) == 0 and len(sub)>=2): prefix_dict[prefix][str(pre)+"_Quantifier"] = True
prefix_dict[prefix][str(pre)+"_Attribute"].append(sub[len(sub) -2]) strings_with_substring_attr = [string for string in data if "isRelatedTo" in string]
sub.pop(len(sub) -2) 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 ):
else: tmp_list = [string for string in data if string not in strings_with_substring_attr]
prefix_dict[prefix][str(pre)+"_Subject"].append(newsub) 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 return prefix_dict
......
...@@ -38,9 +38,9 @@ urlpatterns = [ ...@@ -38,9 +38,9 @@ urlpatterns = [
path('main/choices/shall/', main_req_views.ShallChoicesViewSet.as_view(), name='mainshall'), path('main/choices/shall/', main_req_views.ShallChoicesViewSet.as_view(), name='mainshall'),
#SUFFIX CHOICES DATA #SUFFIX CHOICES DATA
path('suffix/choices/suffix/', suffix_req_views.SuffixChoicesViewSet.as_view(), name='suffixsuffix'), ##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/numunits/', suffix_req_views.NumChoicesViewSet.as_view(), name='suffixnum'),
path('suffix/choices/flow/', suffix_req_views.FlowChoicesViewSet.as_view(), name='suffixflow'), #path('suffix/choices/flow/', suffix_req_views.FlowChoicesViewSet.as_view(), name='suffixflow'),
#Dictionary #Dictionary
path('groupboilerplates/<int:groupboil>/dictionary/', main_req_views.DictionaryViewSet.as_view(), name='dictionary'), path('groupboilerplates/<int:groupboil>/dictionary/', main_req_views.DictionaryViewSet.as_view(), name='dictionary'),
......
...@@ -97,7 +97,9 @@ class MainDetailsAPIView(RetrieveUpdateDestroyAPIView): ...@@ -97,7 +97,9 @@ class MainDetailsAPIView(RetrieveUpdateDestroyAPIView):
if( instance['mumerical_units'] not in numunit_data): if( instance['mumerical_units'] not in numunit_data):
raise APIException("MAIN : Instance of Number Unit does not exist") raise APIException("MAIN : Instance of Number Unit does not exist")
curmain_choices = inference.getclassofmain(instance) 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]") raise APIException("Main choices not in [M1-M16]")
else: else:
instance = serializer.save(main_choices = curmain_choices[0]) instance = serializer.save(main_choices = curmain_choices[0])
...@@ -136,7 +138,7 @@ class MainChoicesAPIView(APIView): ...@@ -136,7 +138,7 @@ class MainChoicesAPIView(APIView):
#print(Dictdata.values('Dictionary_Data')[0]['Dictionary_Data']) #print(Dictdata.values('Dictionary_Data')[0]['Dictionary_Data'])
class_prefix = self.getClassontologyfile(g,es_instance) 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") raise APIException("This instance already exist")
try: 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) )) 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): ...@@ -146,6 +148,7 @@ class MainChoicesAPIView(APIView):
raise APIException("Cannot Add instance") raise APIException("Cannot Add instance")
tempDict = [] tempDict = []
flag = 0 flag = 0
#PROBLEMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
for sao in Dictdata.values('Dictionary_Data')[0]['Dictionary_Data']: for sao in Dictdata.values('Dictionary_Data')[0]['Dictionary_Data']:
if sao['Name'] == es_instance[0].strip(): if sao['Name'] == es_instance[0].strip():
for sao2 in sao['TheClasses']: for sao2 in sao['TheClasses']:
...@@ -154,22 +157,54 @@ class MainChoicesAPIView(APIView): ...@@ -154,22 +157,54 @@ class MainChoicesAPIView(APIView):
for sao3 in sao2['Subclass']: for sao3 in sao2['Subclass']:
if sao3['SubClass_name'] == es_instance[2].strip(): if sao3['SubClass_name'] == es_instance[2].strip():
flag = 2 flag = 2
if(sao3 ['InstanceOfSubclass'] == ''): print(sao3)
sao3 ['InstanceOfSubclass'] = [] for sao4 in sao3['SubSubClass']:
sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment }) if es_instance[3] and sao4['SubSubClass_name'] == es_instance[3].strip():
else: flag =3
sao3['InstanceOfSubclass'].append({"Instance": es_instance[3].strip(), "Comment": comment }) 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 (flag == 1):
if(sao2 ['Instance_of_Class'] == ''): if(sao2 ['Instance_of_Class'] == ''):
print('sao2')
sao2 ['Instance_of_Class'] = [] sao2 ['Instance_of_Class'] = []
sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment }) sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment })
else: else:
sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment }) sao2 ['Instance_of_Class'].append({"Instance": es_instance[2].strip(), "Comment": comment })
if(flag==0): if(flag==0):
sao['GeneralInstances'].append({"Instance": es_instance[1].strip(), "Comment": comment }) sao['GeneralInstances'].append({"Instance": es_instance[1].strip(), "Comment": comment })
print('aaaaaaaaaaaaaaaaa', flag)
tempDict.append(sao) tempDict.append(sao)
Dictdata.update(Dictionary_Data= tempDict) Dictdata.update(Dictionary_Data= tempDict)
if(len(es_instance) == 2):
instance=es_instance[0] +': ' + instance
if (es_instance[0].strip() == 'System'): if (es_instance[0].strip() == 'System'):
m = data.values('system_choices')[0]['system_choices'][:-1] m = data.values('system_choices')[0]['system_choices'][:-1]
if (len(m) ==1 ): if (len(m) ==1 ):
...@@ -204,13 +239,12 @@ class MainChoicesAPIView(APIView): ...@@ -204,13 +239,12 @@ class MainChoicesAPIView(APIView):
return HttpResponse('Update Instance') return HttpResponse('Update Instance')
if (es_instance[0].strip() == 'Flow'): if (es_instance[0].strip() == 'Flow'):
m = data.values('flow_choices')[0]['flow_choices'][:-1] m = data.values('flow_choices')[0]['flow_choices'][:-1]
print('data',m)
if (len(m) ==1 ): if (len(m) ==1 ):
m+= '["'+instance+'","'+instance+'"]'+']' m+= '["'+instance+'","'+instance+'"]'+']'
else : else :
m+= ',["'+instance+'","'+instance+'"]'+']' m+= ',["'+instance+'","'+instance+'"]'+']'
data.update(flow_choices = str(m))
print(m) print(m)
data.update(flow_choices = str(m))
return HttpResponse('Update Instance') return HttpResponse('Update Instance')
if (es_instance[0].strip() == 'State'): if (es_instance[0].strip() == 'State'):
m = data.values('state_choices')[0]['state_choices'][:-1] m = data.values('state_choices')[0]['state_choices'][:-1]
...@@ -236,6 +270,14 @@ class MainChoicesAPIView(APIView): ...@@ -236,6 +270,14 @@ class MainChoicesAPIView(APIView):
m+= ',["'+instance+'","'+instance+'"]'+']' m+= ',["'+instance+'","'+instance+'"]'+']'
data.update(state_value_choices = str(m)) data.update(state_value_choices = str(m))
return HttpResponse('Update Instance') 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): ...@@ -248,10 +290,18 @@ class MainChoicesAPIView(APIView):
raise APIException("There is no file for instances") raise APIException("There is no file for instances")
def getClassontologyfile(self, g, es_instance): def getClassontologyfile(self, g, es_instance):
for ns_prefix, namespace in g.namespaces(): if(len(es_instance) == 2 ):
for s, p, o in g.triples((URIRef( namespace+ es_instance[len(es_instance)-2].strip() ) ,None, None)): for ns_prefix, namespace in g.namespaces():
return URIRef( namespace+ es_instance[len(es_instance)-2].strip() ) 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)):
raise APIException("There is no Class in the Ontology ") 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 ...@@ -14,8 +14,8 @@ from reqman.apps.reqtool.rest_api.services import fuseki
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.views import APIView 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 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 NUMERICAL_AFFIRMATIVE_CHOICES, S2_CHOICES, S3_CHOICES, S4_CHOICES, S5_6_CHOICES
from reqman.apps.reqtool.models.requirements import BoilerplateData from reqman.apps.reqtool.models.requirements import BoilerplateData
...@@ -77,42 +77,6 @@ class SuffixDetailsAPIView(RetrieveUpdateDestroyAPIView): ...@@ -77,42 +77,6 @@ class SuffixDetailsAPIView(RetrieveUpdateDestroyAPIView):
instance.delete() instance.delete()
def getclassofsuffix(self, suffix): def getclassofsuffix(self, suffix):
for sys in NUMERICAL_AFFIRMATIVE_CHOICES: return ("S1")
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")
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