Skip to content

Commit

Permalink
Merge pull request #408 from matthiaskoenig/develop
Browse files Browse the repository at this point in the history
PKDB-v0.6.1 changes
  • Loading branch information
matthiaskoenig authored Jul 1, 2019
2 parents 0a2c003 + d2c0616 commit 882340f
Show file tree
Hide file tree
Showing 22 changed files with 126 additions and 101 deletions.
2 changes: 1 addition & 1 deletion backend/pkdb_app/_version.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""
Definition of version string.
"""
__version__ = "0.6.0"
__version__ = "0.6.1"
4 changes: 4 additions & 0 deletions backend/pkdb_app/analysis/pharmacokinetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ def f_pk(
dose_unit="mg",
vd_unit="L",
bodyweight_unit="kg",
intervention_time = 0,
):
""" Calculates all the pk parameters from given time course.
Expand Down Expand Up @@ -58,6 +59,9 @@ def f_pk(
assert isinstance(c, np.ndarray)
assert t.size == c.size

# caculate all results relative to the intervention time
t = t + intervention_time

# calculate pk
auc = _auc(t, c)
tmax, cmax = _max(t, c)
Expand Down
9 changes: 4 additions & 5 deletions backend/pkdb_app/categorials/behaviours.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,22 +166,21 @@ def normalize(self):
factor, unit = self.remove_substance_dimension()

# remove substance unit

if unit and self.unit:
if ureg(unit) != ureg(self.unit):
for key, value in self.norm_fields.items():
if value is not None:
setattr(self, key, value*factor)
self.unit = unit

else:
self.unit = str(ureg(self.unit).u)
#else:
# self.unit = str(ureg(self.unit).u)

# normalization
if not self.is_norm:
for key, value in self.norm_fields.items():
if not value is None:
setattr(self, key, self.measurement_type.normalize(value, self.unit).magnitude)
self.unit = str(self.measurement_type.norm_unit(self.unit))



self.unit = str(self.measurement_type.norm_unit(self.unit))
13 changes: 8 additions & 5 deletions backend/pkdb_app/categorials/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
"""
import pint
from pint import UndefinedUnitError
import numpy as np

from numbers import Number

from django.db import models
from pkdb_app.categorials.managers import ChoiceManager
from pkdb_app.users.models import User
from pkdb_app.utils import CHAR_MAX_LENGTH, create_choices, _validate_requried_key

ureg = pint.UnitRegistry()

# Units
Expand Down Expand Up @@ -241,8 +242,10 @@ def validate_numeric(self, data):
rule = False

if rule:
raise ValueError({field: f"Numeric values need to be postive for all measurement types but"
f" <{CAN_NEGATIVE_MEASUREMENT_TYPE}>.", "detail":data})
raise ValueError(
{field: f"Numeric values need to be positive (>=0) "
f"for all measurement types except "
f"<{CAN_NEGATIVE_MEASUREMENT_TYPE}>.", "detail":data})

def validate_complete(self, data):
# check unit
Expand All @@ -258,8 +261,8 @@ def validate_complete(self, data):
if time_unit:
self.validate_time_unit(time_unit)

cumulative_measurement_types = ["cumulative amount","cumulative metabolic ratio"]
if self.name in cumulative_measurement_types:
time_requried_measurement_types = ["cumulative amount","cumulative metabolic ratio","recovery"]
if self.name in time_requried_measurement_types:
details = f"for measurement type `{self.name}`"
_validate_requried_key(data,"time", details=details)
_validate_requried_key(data,"time_unit", details=details)
Expand Down
4 changes: 2 additions & 2 deletions backend/pkdb_app/interventions/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class ElasticInterventionViewSet(AccessView):
pagination_class = CustomPagination
lookup_field = "id"
filter_backends = [FilteringFilterBackend,IdsFilterBackend,OrderingFilterBackend,MultiMatchSearchFilterBackend]
search_fields = ('name','measurement_type','substance.name',"form","application",'route','time_unit','normed')
search_fields = ('name','study','access','measurement_type','substance',"form","application",'route','time_unit')
multi_match_search_fields = {field: {"boost": 1} for field in search_fields}
multi_match_options = {
'operator': 'and'
Expand All @@ -60,5 +60,5 @@ class ElasticInterventionViewSet(AccessView):
'choice':'choice.raw',
'normed':'normed',
'application':'application.raw',
'substance':'substance.name',
'substance':'substance.raw',
'value':'value'}
2 changes: 1 addition & 1 deletion backend/pkdb_app/outputs/managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from django.db import models
from django.apps import apps
import time
import pandas as pd
import numpy as np

from pkdb_app.categorials.models import MeasurementType
Expand Down Expand Up @@ -110,6 +109,7 @@ def create(self, *args, **kwargs):
"vd":MeasurementType.objects.get(name="vd"),
}
outputs = []

for key in ["auc", "aucinf", "cl", "cmax", "kel", "thalf", "vd","tmax"]:
pk_unit = pk[f"{key}_unit"]
if not np.isnan(pk[key]):
Expand Down
30 changes: 26 additions & 4 deletions backend/pkdb_app/outputs/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.db import models
from django.contrib.postgres.fields import ArrayField
from pkdb_app.categorials.models import MeasurementType
from pkdb_app.categorials.models import MeasurementType, ureg
from pkdb_app.interventions.models import Intervention

from ..utils import CHAR_MAX_LENGTH, create_choices
Expand Down Expand Up @@ -56,8 +56,7 @@ def outputs(self):
@property
def outputs_normed(self):
outputs = self.outputs.filter(normed=True)
outputs_timecourses = Output.objects.filter(timecourse__in=self.timecourses.all())
return outputs | outputs_timecourses
return outputs

@property
def count_outputs(self):
Expand Down Expand Up @@ -334,8 +333,26 @@ def add_error_measures(self):
if isinstance(cv, np.ndarray):
self.cv = list(cv)


def normalize(self):
"""Normalizes timecourse."""
'''Normalizes timecourse.'''


factor, unit = self.remove_substance_dimension()

if unit:
if ureg(unit) != ureg(self.unit):
for key, value in self.norm_fields.items():
if value is not None:

list_norm_values = list(factor*np.array(value))
setattr(self, key, list_norm_values)
self.unit = unit

else:
self.unit = str(ureg(self.unit).u)



if not self.is_norm:
for key, value in self.norm_fields.items():
Expand All @@ -352,6 +369,7 @@ def normalize(self):
self.time = list(norm_times.m)
self.time_unit = TIME_NORM_UNIT


# for elastic search. NaNs are not allowed in elastic search
@staticmethod
def _any_not_json(value):
Expand Down Expand Up @@ -468,6 +486,10 @@ def get_pharmacokinetic_variables(self):
vd_unit = p_unit_dosing / p_unit_concentration
pk_dict["vd_unit"] = str(vd_unit)
pk_dict["dose"] = dosing.value
if dosing.time:
pk_dict["intervention_time"] = (ureg(dosing.time_unit)*dosing.time).to(self.time_unit).magnitude


pk_dict["dose_unit"] = dosing.unit

# bodyweight dependent values
Expand Down
7 changes: 6 additions & 1 deletion backend/pkdb_app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,10 +288,15 @@ def df_from_file(self, source, format, subset):
if source.isnumeric():
pass
else:
print("here I am")
print(type(source))

raise serializers.ValidationError(
{"source": f"<{str(source)}> is not existing", "detail": type(source)})

else:
raise serializers.ValidationError({"source":f"<{str(source)}> is not existing","detail":type(source)})
raise serializers.ValidationError(
{"source":f"<{str(source)}> is not existing","detail":type(source)})
src = DataFile.objects.get(pk=source)
try:
df = pd.read_csv(
Expand Down
8 changes: 4 additions & 4 deletions backend/pkdb_app/studies/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,14 +374,16 @@ def create_relations(self, study, related):
if related["comments"]:
create_multiple(study, related["comments"], "comments")

study.save()

if "files" in related:
print(related["files"])

study.files.clear()
if related["files"]:
for file_pk in related["files"]:
study.files.add(file_pk)
study.save()

study.save()

return study

Expand Down Expand Up @@ -440,8 +442,6 @@ class Meta:

def get_pdf(self, obj):
user = self.context["request"].user


if get_study_file_permission(user,AttrDict(obj.study)):
return obj.to_dict().get("pdf")
else:
Expand Down
6 changes: 3 additions & 3 deletions backend/pkdb_app/studies/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,9 @@ def update_index_study(request):
related_elastic = related_elastic_dict(study)

for doc, instances in related_elastic.items():
study_related_instances = doc().search().filter("match",study=study.name)
if study_related_instances.count() > 0:
study_related_instances.delete()
#study_related_instances = doc().search().filter("term",study=study.name)
#if study_related_instances.count() > 0:
# study_related_instances.delete()

try:
action = data.get("action", 'index')
Expand Down
1 change: 1 addition & 0 deletions backend/pkdb_app/users/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def get_study_permission(user,obj):


def get_study_file_permission(user,obj):
allow_user_get = False
if isinstance(obj, AttrDict) or isinstance(obj, DictionaryProxy):
username = user.username
curator_usernames = [curator["username"] for curator in obj.curators]
Expand Down
1 change: 1 addition & 0 deletions backend/pkdb_app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ def create_multiple_bulk_normalized(notnormalized_instances, model_class):
return model_class.objects.bulk_create([initialize_normed(notnorm_instance) for notnorm_instance in notnormalized_instances])

def initialize_normed(notnorm_instance):

norm = copy.copy(notnorm_instance)
norm.pk = None
norm.normed = True
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
52 changes: 20 additions & 32 deletions frontend/src/components/Navigation.vue
Original file line number Diff line number Diff line change
@@ -1,14 +1,7 @@
<template>
<v-toolbar id="navigation" class="fixed-nav-bar" flat dense>
<!--
<v-toolbar-side-icon></v-toolbar-side-icon>
<v-toolbar-title class="white--text">PK-DB</v-toolbar-title>
-->
<v-btn icon to="/" title="Home">
<v-icon>{{ icon('home') }}</v-icon>
</v-btn>
<!--<v-spacer></v-spacer>-->

<v-btn icon to="/" title="Home"><v-icon>{{ icon('home') }}</v-icon></v-btn>
<v-btn icon to="/studies" title="Studies"><v-icon>{{ icon('studies') }}</v-icon></v-btn>
<v-btn icon to="/groups" title="Groups"><v-icon>{{ icon('groups') }}</v-icon></v-btn>
<v-btn icon to="/individuals" title="Individuals"><v-icon>{{ icon('individuals') }}</v-icon></v-btn>
Expand All @@ -18,28 +11,22 @@
<v-btn icon to="/references" title="References"><v-icon>{{ icon('references') }}</v-icon></v-btn>

<v-spacer></v-spacer>
<!--user -->
<v-chip v-if="this.$store.state.username" flat>
<user-avatar :username="this.$store.state.username"></user-avatar>
{{this.$store.state.username}}
</v-chip>


<v-dialog v-model="showUserDialog">
<template v-slot:activator="{on}">
<v-btn icon v-on="on">
<v-icon>{{ icon('account') }}</v-icon>
</v-btn>
</template>
<user-login :dialog.sync="showUserDialog" ></user-login>
<!-- account -->
<v-chip v-if="username" flat title="Logout" @click.stop="dialog=true">
<user-avatar :username="username"></user-avatar>
{{ username }}
</v-chip>
<v-btn v-if="username==null" icon title="Login" @click.stop="dialog=true">
<v-icon>{{ icon('account') }}</v-icon>
</v-btn>
<v-dialog v-model="dialog" max-width="500">
<user-login></user-login>
</v-dialog>


<!-- links -->
<v-btn icon to="/curation" title="Curation information"><v-icon>{{ icon('curation') }}</v-icon></v-btn>
<v-btn icon :href="api_url" title="REST API"><v-icon>{{ icon('api') }}</v-icon></v-btn>
<!--
<v-btn icon to="/about" title="About PK-DB"><v-icon>{{ icon('about') }}</v-icon></v-btn>
-->
<v-btn icon :href="admin_url" title="Django admin interface">
<v-icon>{{ icon('admin') }}</v-icon>
</v-btn>
Expand All @@ -55,14 +42,12 @@
export default {
name: 'Navigation',
data(){
return {
showUserDialog : false,
}
},
components: {UserLogin,
components: {
UserLogin,
},
data: () => ({
dialog: false
}),
computed: {
// vuex store
admin_url() {
Expand All @@ -72,6 +57,9 @@
return this.$store.state.endpoints.api;
},
username(){
return this.$store.state.username
}
},
methods: {
icon: function (key) {
Expand Down
Loading

0 comments on commit 882340f

Please sign in to comment.