Commit e4ff295f authored by Thodoris Nestoridis's avatar Thodoris Nestoridis

New inference proccess 1.4.2

parent a80c458d
...@@ -10,11 +10,20 @@ ...@@ -10,11 +10,20 @@
</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%;" <div *ngIf="get_metrics(currentboilerplate.title)"
class="alert alert-warning" role="alert"> style="display:flex; flex-direction: row; align-items: center;margin-bottom: 50px;">
<p [innerHTML]="getinferdata()"></p> <mat-accordion>
<mat-expansion-panel *ngFor="let msection of mes_list" class="alert alert-warning" role="alert">
<mat-expansion-panel-header>
<mat-panel-title [innerHTML]='msection.Description'>
</mat-panel-title>
</mat-expansion-panel-header>
<p [innerHTML]=msection.Title></p>
<p [innerHTML]='msection.Info'></p>
</mat-expansion-panel>
</mat-accordion>
</div> </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">
<label for="title" style="margin-right: 50px;">Requirement title</label> <label for="title" style="margin-right: 50px;">Requirement title</label>
...@@ -138,7 +147,12 @@ ...@@ -138,7 +147,12 @@
{{instan.Instance}} {{instan.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>{{instan.Comment}}</p> <div fxLayout="column">
<p fxFlex fxHide.xs>{{instan.Comment}}</p>
<input fxFlex fxHide.xs fxLayoutAlign="start" class="btn btn-warning" type="button"
value="Delete Instance"
(click)="deleteInstance(section.Name , item.Class, '', '', '', '', instan.Instance, instan.Comment)" />
</div>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </div>
...@@ -205,8 +219,14 @@ ...@@ -205,8 +219,14 @@
<mat-panel-title> <mat-panel-title>
{{ subsubsubsubinstansub.Instance}} {{ subsubsubsubinstansub.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>{{subsubsubsubinstansub.Comment}}</p> <div fxLayout="column">
<p fxFlex fxHide.xs>{{subsubsubsubinstansub.Comment}}</p>
<input fxFlex fxHide.xs fxLayoutAlign="start" class="btn btn-warning" type="button"
value="Delete Instance"
(click)="deleteInstance(section.Name , item.Class, sub.SubClass_name, subsub.SubSubClass_name , subsubsub.SubSubClass_name, subsubsubsub.SubSubClass_name, subsubsubsubinstansub.Instance, subsubsubsubinstansub.Comment)" />
</div>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </div>
...@@ -227,7 +247,12 @@ ...@@ -227,7 +247,12 @@
{{ subsubsubinstansub.Instance}} {{ subsubsubinstansub.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>{{subsubsubinstansub.Comment}}</p> <div fxLayout="column">
<p fxFlex fxHide.xs>{{subsubsubinstansub.Comment}}</p>
<input fxFlex fxHide.xs fxLayoutAlign="start" class="btn btn-warning" type="button"
value="Delete Instance"
(click)="deleteInstance(section.Name , item.Class, sub.SubClass_name, subsub.SubSubClass_name , subsubsub.SubSubClass_name, '', subsubsubinstansub.Instance, subsubsubinstansub.Comment)" />
</div>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </div>
...@@ -248,7 +273,12 @@ ...@@ -248,7 +273,12 @@
{{ subsubinstansub.Instance}} {{ subsubinstansub.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>{{subsubinstansub.Comment}}</p> <div fxLayout="column">
<p fxFlex fxHide.xs>{{subsubinstansub.Comment}}</p>
<input fxFlex fxHide.xs fxLayoutAlign="start" class="btn btn-warning" type="button"
value="Delete Instance"
(click)="deleteInstance(section.Name , item.Class, sub.SubClass_name, subsub.SubSubClass_name , '', '', subsubinstansub.Instance, subsubinstansub.Comment)" />
</div>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </div>
...@@ -270,7 +300,12 @@ ...@@ -270,7 +300,12 @@
{{ instansub.Instance}} {{ instansub.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
<p>{{instansub.Comment}}</p> <div fxLayout="column">
<p fxFlex fxHide.xs>{{instansub.Comment}}</p>
<input fxFlex fxHide.xs fxLayoutAlign="start" class="btn btn-warning" type="button"
value="Delete Instance"
(click)="deleteInstance(section.Name , item.Class, sub.SubClass_name, '', '', '', instansub.Instance, instansub.Comment)" />
</div>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
...@@ -297,7 +332,11 @@ ...@@ -297,7 +332,11 @@
{{genin.Instance}} {{genin.Instance}}
</mat-panel-title> </mat-panel-title>
</mat-expansion-panel-header> </mat-expansion-panel-header>
{{genin.Comment}} <div fxLayout="column">
<p fxFlex fxHide.xs> {{genin.Comment}}</p>
<input fxFlex fxHide.xs fxLayoutAlign="start" class="btn btn-warning" type="button" value="Delete Instance"
(click)="deleteInstance(section.Name , '', '', '' , '', '', genin.Instance, genin.Comment)" />
</div>
</mat-expansion-panel> </mat-expansion-panel>
</li> </li>
</div> </div>
......
...@@ -42,7 +42,7 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -42,7 +42,7 @@ export class BoilerplateDetailsComponent implements OnInit {
searchText = ''; searchText = '';
searchTextinstances = ''; searchTextinstances = '';
addinstance = ''; addinstance = '';
mes_list = [] as any;
private readonly notifier: NotifierService; private readonly notifier: NotifierService;
...@@ -137,7 +137,7 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -137,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
}, },
...@@ -148,26 +148,38 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -148,26 +148,38 @@ export class BoilerplateDetailsComponent implements OnInit {
details_metrics = ["isMissingConcept", "isMissingInstanceOf", "isMissingProducer", "isMissingState", "hasAmbiguousConcept", "hasAmbiguousConcept2", details_metrics = ["isMissingConcept", "isMissingInstanceOf", "isMissingProducer", "isMissingState", "hasAmbiguousConcept", "hasAmbiguousConcept2",
"hasNoisyConcept", "hasOpaqueConcept", "isInconsistentTo"] "hasNoisyConcept", "hasOpaqueConcept", "isInconsistentTo"]
getinferdata(): any { getinferdata(): any {
let message = ""
if (this.currentInfer && this.currentboilerplate.title) { if (this.currentInfer && this.currentboilerplate.title && this.mes_list.length == 0) {
const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\"")) const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
this.mes_list = []
for (let i of this.details_metrics) { for (let i of this.details_metrics) {
let title = ""
let description = ""
let information = ""
if (obj[i][0][this.currentboilerplate.title]?.length > 0) { 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>' title = '<b>Description : </b>' + obj[i][0]['Comment']
description = 'Invalid instances: ' + '<b>' + obj[i][0][this.currentboilerplate.title] + '</b>'
for (let instances of obj[i][0][this.currentboilerplate.title]) {
information += 'Above there are presented the DSO properties for the instance : <b>' + instances + '</b>'
for (let info of obj[i][0][instances]) { information += '<ul><li>' + info + '</ul></li>' }
}
}
if (title != '' && description != "" && information != "") {
this.mes_list.push({ 'Title': title, 'Description': description, 'Info': information })
} }
} }
return message
} }
} }
get_metrics(i: any): any { get_metrics(i: any): any {
if (this.currentInfer?.inference_data) { if (this.currentInfer?.inference_data) {
const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\"")) const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
if (obj[i]) { if (obj[i]?.length > 0) {
this.getinferdata();
return true return true
} }
} }
return 0 return false
} }
checklen(i: any): any { checklen(i: any): any {
...@@ -177,6 +189,145 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -177,6 +189,145 @@ export class BoilerplateDetailsComponent implements OnInit {
return false return false
} }
deleteInstance(section: any, classes: any, subclass: any, subsubclass: any, subsubsubclass: any, subsubsubsubclass: any, instance: any, comment: any): void {
if (confirm("Αre you sure you want to delete this Instance?")) {
const removeinstance = section + (classes ? ' : ' + classes : '') + (subclass ? ' : ' + subclass : '') + (subsubclass ? ' : ' + subsubclass : '') + (subsubsubclass ? ' : ' + subsubsubclass : '') + (subsubsubsubclass ? ' : ' + subsubsubsubclass : '') + ' : ' + instance;
this.mainService.deleteinstances(this.route.snapshot.params.gb, removeinstance, (comment ? comment : ' '))
.subscribe(
response => {
this.prefchild.getchoices(this.route.snapshot.params.gb);
this.mainchild.getmainchoices(this.route.snapshot.params.gb);
this.sufchild.getflowchoices(this.route.snapshot.params.gb);
},
error => {
if (error.error.text == 'Instance deleted') {
this.notifier.notify("success", (JSON.stringify(error.error.text)));
if (this.systems) {
this.systems.forEach(function (value) {
if (section == value.Name) {
if (value.TheClasses) {
value.TheClasses.forEach(function (value) {
if (classes == value.Class) {
//UI - Add instance of a Class (e.g instance for System : Vehicle)
if (!subclass && !subsubclass) {
if (value.Instance_of_Class) {
let data_item = { 'Instance': instance, 'Comment': comment }
value.Instance_of_Class = value.Instance_of_Class.filter(item => (JSON.stringify(data_item) != JSON.stringify(item)
))
}
}
}
//UI - Add instance of a SubClass (e.g instance for System : Software : Plan)
if (subclass && !subsubclass) {
if (value.Subclass) {
value.Subclass.forEach(function (value) {
if (subclass == value.SubClass_name) {
if (value.InstanceOfSubclass) {
let data_item = { 'Instance': instance, 'Comment': comment }
value.InstanceOfSubclass = value.InstanceOfSubclass.filter(item => (JSON.stringify(data_item) != JSON.stringify(item)
))
}
}
})
}
}
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) {
let data_item = { 'Instance': instance, 'Comment': comment }
value1.SubInstanceOfSubclass = value1.SubInstanceOfSubclass.filter(item => (JSON.stringify(data_item) != JSON.stringify(item)
))
}
}
})
}
}
})
}
}
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) {
let data_item = { 'Instance': instance, 'Comment': comment }
value2.SubInstanceOfSubclass = value2.SubInstanceOfSubclass.filter(item => (JSON.stringify(data_item) != JSON.stringify(item)
))
}
}
})
}
}
})
}
}
})
}
}
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.SubSubClass_name == subsubsubsubclass) {
if (value3.SubInstanceOfSubclass) {
let data_item = { 'Instance': instance, 'Comment': comment }
value3.SubInstanceOfSubclass = value3.SubInstanceOfSubclass.filter(item => (JSON.stringify(data_item) != JSON.stringify(item)
))
}
}
})
}
}
})
}
}
})
}
}
})
}
}
});
}
if (!classes) {
let data_item = { 'Instance': instance, 'Comment': comment }
if (value.GeneralInstances) {
value.GeneralInstances = value.GeneralInstances.filter(item => (JSON.stringify(data_item) != JSON.stringify(item)))
}
}
}
})
}
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); }
} else { this.notifier.notify("warning", (JSON.stringify(error.error.detail))); }
});
}
}
currentDialog: DialogData = { currentDialog: DialogData = {
instance: "", instance: "",
comment: "", comment: "",
...@@ -301,19 +452,19 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -301,19 +452,19 @@ export class BoilerplateDetailsComponent implements OnInit {
if (value2.SubSubClass_name == subsubsubclass) { if (value2.SubSubClass_name == subsubsubclass) {
if (value2.SubSubClass) { if (value2.SubSubClass) {
value2.SubSubClass.forEach(function (value3) { value2.SubSubClass.forEach(function (value3) {
if (value3.SubInstanceOfSubclass) { if (value3.SubSubClass_name == subsubsubsubclass) {
value3.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }) if (value3.SubInstanceOfSubclass) {
} else { value3.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
value3.SubInstanceOfSubclass = []; } else {
value3.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " }) value3.SubInstanceOfSubclass = [];
value3.SubInstanceOfSubclass.push({ "Instance": result.instance, "Comment": result.comment ? result.comment : " " })
}
} }
}) })
} }
} }
}) })
} }
} }
}) })
} }
...@@ -334,8 +485,6 @@ export class BoilerplateDetailsComponent implements OnInit { ...@@ -334,8 +485,6 @@ export class BoilerplateDetailsComponent implements OnInit {
if (this.prefchild) { this.prefchild.getchoices(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.mainchild) { this.mainchild.getmainchoices(this.route.snapshot.params.gb); }
if (this.sufchild) { this.sufchild.getflowchoices(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();
......
...@@ -135,9 +135,9 @@ export class MainDetailsComponent implements OnInit { ...@@ -135,9 +135,9 @@ export class MainDetailsComponent implements OnInit {
} }
ngOnInit(): void { ngOnInit(): void {
this.getAllMain(this.route.snapshot.params.id);
this.getchoices(); this.getchoices();
this.getmainchoices(this.route.snapshot.params.gb); this.getmainchoices(this.route.snapshot.params.gb);
this.getAllMain(this.route.snapshot.params.id);
} }
ngDoCheck() { ngDoCheck() {
......
...@@ -169,4 +169,8 @@ export class MainService { ...@@ -169,4 +169,8 @@ export class MainService {
setinstances(gb : any, instance: any, comment:any): Observable<any> { setinstances(gb : any, instance: any, comment:any): Observable<any> {
return this.http.get(`${baseUrl2}${gb}`+`/main/choices/add`+`/${instance}`+`/${comment}/`); return this.http.get(`${baseUrl2}${gb}`+`/main/choices/add`+`/${instance}`+`/${comment}/`);
} }
deleteinstances(gb : any, instance: any, comment:any): Observable<any> {
return this.http.get(`${baseUrl2}${gb}`+`/main/choices/delete`+`/${instance}`+`/${comment}/`);
}
} }
...@@ -121,21 +121,21 @@ class Main(models.Model): ...@@ -121,21 +121,21 @@ class Main(models.Model):
boilerplate_of_main = models.ForeignKey('reqtool.Boilerplate', related_name='main_boilerplate', on_delete=models.CASCADE) boilerplate_of_main = models.ForeignKey('reqtool.Boilerplate', related_name='main_boilerplate', on_delete=models.CASCADE)
main_owner = models.ForeignKey(User, related_name='main_owner', on_delete=models.CASCADE) main_owner = models.ForeignKey(User, related_name='main_owner', on_delete=models.CASCADE)
#Subject #Subject
sys_fun_inter = models.CharField(max_length=100) sys_fun_inter = models.CharField(max_length=1000)
#Between Subject - Verb #Between Subject - Verb
state_item_before_verb = models.CharField(max_length=100, blank=True) state_item_before_verb = models.CharField(max_length=1000, blank=True)
statevalue_before_verb = models.CharField(max_length=100, blank=True) statevalue_before_verb = models.CharField(max_length=1000, blank=True)
#Verb #Verb
shall = models.CharField(max_length=100) shall = models.CharField(max_length=1000)
verb = models.CharField(max_length=100) verb = models.CharField(max_length=1000)
#Between Verb - Object #Between Verb - Object
quantifier = models.CharField(max_length=100, blank=True) quantifier = models.CharField(max_length=1000, blank=True)
numerical = models.CharField(blank=True, null=True, max_length=10) numerical = models.CharField(blank=True, null=True, max_length=1000)
mumerical_units = models.CharField(max_length=100, blank=True) mumerical_units = models.CharField(max_length=1000, blank=True)
#Οbject #Οbject
flow_function_interface_item_system_state_stateset = models.CharField( max_length=100) flow_function_interface_item_system_state_stateset = models.CharField( max_length=1000)
#last definitions #last definitions
statevalue_system_connection_stateset = models.CharField(max_length=100, blank=True) statevalue_system_connection_stateset = models.CharField(max_length=1000, blank=True)
#ID [M1-M16] #ID [M1-M16]
main_choices = models.CharField(max_length=100, blank=True) main_choices = models.CharField(max_length=100, blank=True)
......
...@@ -158,7 +158,7 @@ class Boilerplate(models.Model): ...@@ -158,7 +158,7 @@ class Boilerplate(models.Model):
owner = models.ForeignKey(User, related_name='boilerplate', on_delete=models.CASCADE) owner = models.ForeignKey(User, related_name='boilerplate', on_delete=models.CASCADE)
group_of_boilerplate = models.ForeignKey(BoilerplateGroup, related_name='owner_of_boilerplate', on_delete=models.CASCADE) group_of_boilerplate = models.ForeignKey(BoilerplateGroup, related_name='owner_of_boilerplate', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True) created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=30, unique=True) title = models.CharField(max_length=300, unique=True)
has_prefix = models.BooleanField(default=False) has_prefix = models.BooleanField(default=False)
has_main = models.BooleanField(default=False) has_main = models.BooleanField(default=False)
has_suffix = models.BooleanField(default=False) has_suffix = models.BooleanField(default=False)
...@@ -212,18 +212,18 @@ class PrefixGroup(models.Model): ...@@ -212,18 +212,18 @@ class PrefixGroup(models.Model):
class Prefix(models.Model): class Prefix(models.Model):
prefixgroup = models.ForeignKey(PrefixGroup, related_name='prefix', on_delete=models.CASCADE) prefixgroup = models.ForeignKey(PrefixGroup, related_name='prefix', on_delete=models.CASCADE)
prefix_boilerplate = models.ForeignKey(Boilerplate, related_name='prefix_boilerplate', on_delete=models.CASCADE) prefix_boilerplate = models.ForeignKey(Boilerplate, related_name='prefix_boilerplate', on_delete=models.CASCADE)
prefix = models.CharField(max_length=100) prefix = models.CharField(max_length=1000)
#state value constraint #state value constraint
system_fun_item = models.CharField(max_length=100) system_fun_item = models.CharField(max_length=1000)
state_or_verb = models.CharField(max_length=100) state_or_verb = models.CharField(max_length=1000)
#occuring functionality #occuring functionality
item_function_flow_statevalue = models.CharField(max_length=100) item_function_flow_statevalue = models.CharField(max_length=1000)
#state value constraint OR occuring functionality #state value constraint OR occuring functionality
logical_expression = models.CharField(max_length=100, blank=True) logical_expression = models.CharField(max_length=1000, blank=True)
#Logic connectivity Prefix1 (and/or/xor) Prefix2 #Logic connectivity Prefix1 (and/or/xor) Prefix2
logic_connective = models.CharField(max_length=100, blank=True) logic_connective = models.CharField(max_length=1000, blank=True)
#Prefix value P1/P2/P3 #Prefix value P1/P2/P3
simple_prefix = models.CharField(max_length=100, blank=True) simple_prefix = models.CharField(max_length=1000, blank=True)
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
...@@ -265,7 +265,7 @@ class BoilerplateData(models.Model): ...@@ -265,7 +265,7 @@ class BoilerplateData(models.Model):
class InferenceResults(models.Model): class InferenceResults(models.Model):
owner_infer = models.ForeignKey(User, related_name='owner_infer', on_delete=models.CASCADE) owner_infer = models.ForeignKey(User, related_name='owner_infer', on_delete=models.CASCADE)
infer_group_of_boilerplate = models.ForeignKey(BoilerplateGroup, related_name='infer_owner_of_boilerplate', on_delete=models.CASCADE) infer_group_of_boilerplate = models.ForeignKey(BoilerplateGroup, related_name='infer_owner_of_boilerplate', on_delete=models.CASCADE)
ontology_file = models.CharField(max_length=100, blank=True) ontology_file = models.CharField(max_length=1000, blank=True)
inference_data = models.CharField(default="", max_length=1000000, blank=True) inference_data = models.CharField(default="", max_length=1000000, blank=True)
def save(self, **kwargs): def save(self, **kwargs):
...@@ -280,7 +280,7 @@ class InferenceResults(models.Model): ...@@ -280,7 +280,7 @@ class InferenceResults(models.Model):
class BoilerplateGroupClassesInstances(models.Model): class BoilerplateGroupClassesInstances(models.Model):
classes_instances_group_of_boilerplate = models.ForeignKey(BoilerplateGroup, related_name='classes_instances_owner_of_boilerplate', on_delete=models.CASCADE) classes_instances_group_of_boilerplate = models.ForeignKey(BoilerplateGroup, related_name='classes_instances_owner_of_boilerplate', on_delete=models.CASCADE)
classes_instances_owner = models.ForeignKey(User, related_name='classes_instances_owner', on_delete=models.CASCADE) classes_instances_owner = models.ForeignKey(User, related_name='classes_instances_owner', on_delete=models.CASCADE)
ontology_file = models.CharField(default="", max_length=100, blank=True) ontology_file = models.CharField(default="", max_length=1000, blank=True)
prefix_choices = JSONField() prefix_choices = JSONField()
prefix_logcon_choices = JSONField() prefix_logcon_choices = JSONField()
prefix_verb_choices = JSONField() prefix_verb_choices = JSONField()
...@@ -306,5 +306,5 @@ class BoilerplateGroupClassesInstances(models.Model): ...@@ -306,5 +306,5 @@ class BoilerplateGroupClassesInstances(models.Model):
class BoilerplateGroupDictionary(models.Model): class BoilerplateGroupDictionary(models.Model):
classes_instances_group_of_boilerplate_dic = models.ForeignKey(BoilerplateGroup, related_name='classes_instances_owner_of_boilerplate_dic', on_delete=models.CASCADE) classes_instances_group_of_boilerplate_dic = models.ForeignKey(BoilerplateGroup, related_name='classes_instances_owner_of_boilerplate_dic', on_delete=models.CASCADE)
classes_instances_owner_dic = models.ForeignKey(User, related_name='classes_instances_owner_dic', on_delete=models.CASCADE) classes_instances_owner_dic = models.ForeignKey(User, related_name='classes_instances_owner_dic', on_delete=models.CASCADE)
ontology_file_dic = models.CharField(default="", max_length=100, blank=True) ontology_file_dic = models.CharField(default="", max_length=1000, blank=True)
Dictionary_Data = JSONField() Dictionary_Data = JSONField()
...@@ -82,10 +82,10 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix): ...@@ -82,10 +82,10 @@ 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))
for i in range(len(boilerplate)): for i in range(len(boilerplate)):
title = boilerplate[i][0]['title'] title = boilerplate[i][0]['title']
g.add((per_instances + title, RDF.type, rdo + 'Requirement')) g.add((per_instances + title, RDF.type, rdo + 'Requirement'))
...@@ -135,7 +135,6 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix): ...@@ -135,7 +135,6 @@ def exportboiltottl(ontfile,project, prefix, boilerplate, main, suffix):
if(main[i][0][j] != ""): 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)
if ( splitter_1[0] =='Item' or splitter_1[0] =='Flow' ): if ( splitter_1[0] =='Item' or splitter_1[0] =='Flow' ):
print(main[i][0][j])
g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToTraversingConcept", URIRef(str(instance_file))+"#"+ str(splitter_1[len(splitter_1) -1]))) g.add((per_instances+(title+"_"+ main[i][0]['main_choices']), rbo+"isRelatedToTraversingConcept", URIRef(str(instance_file))+"#"+ str(splitter_1[len(splitter_1) -1])))
else : 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])))
...@@ -253,36 +252,62 @@ def shacl(ontotlogy_file): ...@@ -253,36 +252,62 @@ def shacl(ontotlogy_file):
open(target, 'w').close() open(target, 'w').close()
shutil.copyfile(file1, target) shutil.copyfile(file1, target)
for i in range(3): for i in range(3):
print(i+1, 'Cycle of inferencing') print(i+1, 'Cycle of inferencing')
result = subprocess.check_output(["./reqman/apps/reqtool/rest_api/services/shacl-1.3.2/bin/shaclinfer.sh", "-datafile", target]) #result = subprocess.check_output(["./reqman/apps/reqtool/rest_api/services/shacl-1.3.2/bin/shaclinfer.sh", "-datafile", target])
file_object = open(target, 'a') try:
res = str(result,'utf-8') result = subprocess.check_output("./reqman/apps/reqtool/rest_api/services/shacl-1.4.2/bin/shaclinfer.sh -datafile "+target+" | grep -v -e 'WARN OntDocumentManager' -e 'at org.' -e 'org.apache.' -e '@'",shell=True)
file_object.write(res.strip()) except:
file_object.close() raise APIException("Problem during the Inferencing")
file_object = open(target, 'a')
res = str(result,'utf-8')
file_object.write(res.strip())
file_object.close()
#need to fiil with all the metrics #need to fiil with all the metrics
g = Graph() g = Graph()
gon = Graph()
g.load(target, format="turtle") g.load(target, format="turtle")
gon.load(ontotlogy_file, format="turtle")
req_list=[]
for inf_metr in list_of_inference_metrics: for inf_metr in list_of_inference_metrics:
metrics_dict[inf_metr] = [] metrics_dict[inf_metr] = []
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO#"+inf_metr) p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO#"+inf_metr)
for s, p, o in g.triples((None, RDF.type, p)): for s, p, o in g.triples((None, RDF.type, p)):
#metrics_dict["IncompleteRequirement"] = [s] # e.g IncompleteRequirement': ['Req1', 'Req2']
get_title = str(s).split("#") get_title = str(s).split("#")
if get_title[1] not in req_list:
req_list.append(get_title[1])
metrics_dict[inf_metr].append(get_title[1]) metrics_dict[inf_metr].append(get_title[1])
for inf_metr2 in info_metric:
metrics_dict[inf_metr2] = [] for inf_metr2 in info_metric:
p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO#"+inf_metr2) #e.g isMissingOfInstance : ['Comment' : '...', {'Req1':['Instance1']}, {'Req2':['Instance2']}]
req_dict={} metrics_dict[inf_metr2] = []
req_dict['Comment'] = "" p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO#"+inf_metr2)
for scom, pcom, ocom in g.triples((p, RDFS.comment, None)): req_dict={}
req_dict['Comment'] = str(ocom) req_dict['Comment'] = ""
req_dict[get_title[1]]=[] for scom, pcom, ocom in g.triples((p, RDFS.comment, None)):
for s1, p1, o1 in g.triples((s, p, None)): req_dict['Comment'] = str(ocom)
get_title2 = str(o1).split("#") for get_title in req_list:
req_dict[get_title[1]].append(get_title2[1]) req_dict[get_title]=[]
metrics_dict[inf_metr2].append(req_dict) s = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO-instances#"+get_title)
print(metrics_dict) p = URIRef("http://delab.csd.auth.gr/ontologies/2018/RDO#"+inf_metr2)
for s1, p1, o1 in g.triples((s, p, None)):
get_title2 = str(o1).split("#")
req_dict[get_title].append(get_title2[1])
req_dict[get_title2[1]]=[]
for s3, p3, o3 in gon.triples((None, None, o1)):
sub=str(s3).split("#")
ver=str(p3).split("#")
obj=str(o3).split("#")
req_dict[get_title2[1]].append(sub[1]+' '+ ver[1]+' '+ obj[1])
for s3, p3, o3 in gon.triples((o1, None, None)):
sub=str(s3).split("#")
ver=str(p3).split("#")
obj=str(o3).split("#")
req_dict[get_title2[1]].append('<i>'+sub[1]+'</i> <u>'+ ver[1]+'</u> <i>'+obj[1]+'</i>')
metrics_dict[inf_metr2].append(req_dict)
#print(metrics_dict)
return(metrics_dict) return(metrics_dict)
......
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
## Licensed under the terms of http://www.apache.org/licenses/LICENSE-2.0
status = error
name = PropertiesConfig
filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = ALL
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{HH:mm:ss} %-5p %-10c{1} :: %m%n
#appender.console.layout.pattern = [%d{yyyy-MM-dd HH:mm:ss}] %-5p %-10c{1} :: %m%n
rootLogger.level = INFO
rootLogger.appenderRef.stdout.ref = STDOUT
logger.jena.name = org.apache.jena
logger.jena.level = WARN
logger.arq-info.name = org.apache.jena.arq.info
logger.arq-info.level = INFO
logger.riot.name = org.apache.jena.riot
logger.riot.level = INFO
...@@ -35,6 +35,7 @@ urlpatterns = [ ...@@ -35,6 +35,7 @@ urlpatterns = [
#MAIN CHOICES DATA #MAIN CHOICES DATA
path('groupboilerplates/<int:groupboil>/main/choices/', main_req_views.MainChoicesViewSet.as_view(), name='mainchoices'), path('groupboilerplates/<int:groupboil>/main/choices/', main_req_views.MainChoicesViewSet.as_view(), name='mainchoices'),
path('groupboilerplates/<int:groupboil>/main/choices/add/<str:instance>/<str:comment>/', main_req_views.MainChoicesAPIView.as_view(), name='setmainchoices'), path('groupboilerplates/<int:groupboil>/main/choices/add/<str:instance>/<str:comment>/', main_req_views.MainChoicesAPIView.as_view(), name='setmainchoices'),
path('groupboilerplates/<int:groupboil>/main/choices/delete/<str:instance>/<str:comment>/', main_req_views.DeleteMainChoicesAPIView.as_view(), name='deletemainchoices'),
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
......
...@@ -148,7 +148,7 @@ class MainChoicesAPIView(APIView): ...@@ -148,7 +148,7 @@ class MainChoicesAPIView(APIView):
raise APIException("Cannot Add instance") raise APIException("Cannot Add instance")
tempDict = [] tempDict = []
flag = 0 flag = 0
#PROBLEMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM #Add instance to Dictrionary
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']:
...@@ -157,7 +157,6 @@ class MainChoicesAPIView(APIView): ...@@ -157,7 +157,6 @@ 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
print(sao3)
for sao4 in sao3['SubSubClass']: for sao4 in sao3['SubSubClass']:
if es_instance[3] and sao4['SubSubClass_name'] == es_instance[3].strip(): if es_instance[3] and sao4['SubSubClass_name'] == es_instance[3].strip():
flag =3 flag =3
...@@ -184,7 +183,7 @@ class MainChoicesAPIView(APIView): ...@@ -184,7 +183,7 @@ class MainChoicesAPIView(APIView):
sao4 ['SubInstanceOfSubclass'] = [] sao4 ['SubInstanceOfSubclass'] = []
sao4['SubInstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment }) sao4['SubInstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment })
else: else:
sao4['InstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment }) sao4['SubInstanceOfSubclass'].append({"Instance": es_instance[4].strip(), "Comment": comment })
# SubSubClass_name # SubSubClass_name
if(flag == 2): if(flag == 2):
if(sao3 ['InstanceOfSubclass'] == ''): if(sao3 ['InstanceOfSubclass'] == ''):
...@@ -200,7 +199,6 @@ class MainChoicesAPIView(APIView): ...@@ -200,7 +199,6 @@ class MainChoicesAPIView(APIView):
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): if(len(es_instance) == 2):
...@@ -243,7 +241,6 @@ class MainChoicesAPIView(APIView): ...@@ -243,7 +241,6 @@ class MainChoicesAPIView(APIView):
m+= '["'+instance+'","'+instance+'"]'+']' m+= '["'+instance+'","'+instance+'"]'+']'
else : else :
m+= ',["'+instance+'","'+instance+'"]'+']' m+= ',["'+instance+'","'+instance+'"]'+']'
print(m)
data.update(flow_choices = str(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'):
...@@ -278,6 +275,138 @@ class MainChoicesAPIView(APIView): ...@@ -278,6 +275,138 @@ class MainChoicesAPIView(APIView):
m+= ',["'+instance+'","'+instance+'"]'+']' m+= ',["'+instance+'","'+instance+'"]'+']'
data.update(connection_choices = str(m)) data.update(connection_choices = str(m))
return HttpResponse('Update Instance') return HttpResponse('Update Instance')
def getontologyfile(self, g):
for ns_prefix, namespace in g.namespaces():
if ('DSO' in namespace and 'instance' in namespace):
return namespace
raise APIException("There is no file for instances")
def getClassontologyfile(self, g, es_instance):
if(len(es_instance) == 2 ):
for ns_prefix, namespace in g.namespaces():
for s, p, o in g.triples((URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
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 ")
class DeleteMainChoicesAPIView(APIView):
def get(self, request, groupboil, instance, comment, format=None):
data = BoilerplateGroupClassesInstances.objects.filter(classes_instances_group_of_boilerplate = groupboil)
Dictdata = BoilerplateGroupDictionary.objects.filter(classes_instances_group_of_boilerplate_dic = groupboil)
g = Graph()
g.load(data.values('ontology_file')[0]['ontology_file'], format="turtle")
#onotlogy_prefix=self.getontologyfile(g)
es_instance = instance.rsplit(':')
#print(Dictdata.values('Dictionary_Data')[0]['Dictionary_Data'])
exist = 0
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))):
exist =1
if( exist ==0 ):
raise APIException("This instance cannot be deleted or it not exists")
try:
g.remove(( URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , None, None ))
g.remove(( URIRef( "http://delab.csd.auth.gr/ontologies/2018/RDO-instances#" + es_instance[len(es_instance)-1].strip() ) , RDFS.comment , None))
g.serialize(data.values('ontology_file')[0]['ontology_file'], format='turtle')
except:
raise APIException("Cannot delete instance")
tempDict = []
flag = 0
#Add instance to Dictrionary
for sao in Dictdata.values('Dictionary_Data')[0]['Dictionary_Data']:
if sao['Name'] == es_instance[0].strip():
for sao2 in sao['TheClasses']:
if sao2['Class'] == es_instance[1].strip():
flag = 1
for sao3 in sao2['Subclass']:
if sao3['SubClass_name'] == es_instance[2].strip():
flag = 2
for sao4 in sao3['SubSubClass']:
if es_instance[3] and sao4['SubSubClass_name'] == es_instance[3].strip():
flag =3
for sao5 in sao4['SubSubClass']:
if es_instance[4] and sao5['SubSubClass_name'] == es_instance[4].strip():
flag =4
for sao6 in sao5['SubSubClass']:
if es_instance[5] and sao6['SubSubClass_name'] == es_instance[5].strip():
flag = 5
if(flag == 5):
sao6['SubInstanceOfSubclass'].remove({"Instance": es_instance[6].strip(), "Comment": comment })
if(flag == 4):
sao5['SubInstanceOfSubclass'].remove({"Instance": es_instance[5].strip(), "Comment": comment })
if(flag == 3):
sao4['SubInstanceOfSubclass'].remove({"Instance": es_instance[4].strip(), "Comment": comment })
# SubSubClass_name
if(flag == 2):
sao3['InstanceOfSubclass'].remove({"Instance": es_instance[3].strip(), "Comment": comment })
if (flag == 1):
sao2 ['Instance_of_Class'].remove({"Instance": es_instance[2].strip(), "Comment": comment })
if(flag==0):
sao['GeneralInstances'].remove({"Instance": es_instance[1].strip(), "Comment": comment })
tempDict.append(sao)
Dictdata.update(Dictionary_Data= tempDict)
if(len(es_instance) == 2):
instance=es_instance[0] +': ' + instance
if (es_instance[0].strip() == 'System'):
m = data.values('system_choices')[0]['system_choices']
if (instance in m) :
m = m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(system_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'Function'):
m = data.values('function_choices')[0]['function_choices']
if (instance in m) :
m = m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(function_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'Item'):
m = data.values('item_choices')[0]['item_choices']
if (instance in m) :
m = m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(item_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'Interface'):
m = data.values('inteface_choices')[0]['inteface_choices']
if (instance in m) :
m= m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(inteface_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'Flow'):
m = data.values('flow_choices')[0]['flow_choices']
if (instance in m) :
m= m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(flow_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'State'):
m = data.values('state_choices')[0]['state_choices']
if (instance in m) :
m= m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(state_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'StateSet'):
m = data.values('state_set_choices')[0]['state_set_choices']
if (instance in m) :
m= m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(state_set_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'StateValue'):
m = data.values('state_value_choices')[0]['state_value_choices']
if (instance in m) :
m= m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(state_value_choices = str(m))
return HttpResponse('Instance deleted')
if (es_instance[0].strip() == 'Connection'):
m = data.values('connection_choices')[0]['connection_choices']
if (instance in m) :
m= m.replace(',["'+instance+'","'+instance+'"]', '')
data.update(connection_choices = str(m))
return HttpResponse('Instance deleted')
...@@ -293,7 +422,6 @@ class MainChoicesAPIView(APIView): ...@@ -293,7 +422,6 @@ class MainChoicesAPIView(APIView):
if(len(es_instance) == 2 ): if(len(es_instance) == 2 ):
for ns_prefix, namespace in g.namespaces(): for ns_prefix, namespace in g.namespaces():
for s, p, o in g.triples((URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() ) ,None, None)): for s, p, o in g.triples((URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() ) ,None, None)):
print(p,s)
return URIRef( 'http://delab.csd.auth.gr/ontologies/2018/SAO#'+ es_instance[len(es_instance)-2].strip() ) 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 ") raise APIException("There is no Class in the Ontology ")
else: else:
......
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