Unisens / pyunisens

Python library to handle Unisens data
MIT License
4 stars 3 forks source link

Add new custom attributes #4

Closed JoshM94 closed 3 years ago

JoshM94 commented 3 years ago

Hi, I want to add a new custom attribute with one key & one value as result in unisens. I tried different code. The following overwrites all custom attributes and adds only the new one.

from unisens import CustomAttributes
import unisens as uni

unisens = uni.Unisens('C:/Users/Josua/Desktop/example1')    # in this folder is a unisens file
value_ecg_hr_inactive = 101.0              # usually i get the values from a dataframe, but it doesn't matter here

unisens.add_entry(CustomAttributes(key='ecg_hr_inactive', value=value_ecg_hr_inactive))  # overwrites all custom attributes, which are listed before. Only the new custom attribute is added.
unisens.save()

I also tried other code with MiscEntry as Input of add_entry

from unisens import MiscEntry
import unisens as uni

unisens = uni.Unisens('C:/Users/Josua/Desktop/example1')
value_ecg_hr_inactive = 101.0

hr_inactive_miscentry = MiscEntry(name='customAttribute', key='ecg_hr_inactive', value=str(value_ecg_hr_inactive))
CustomAttributes(key='ecg_hr_inactive', value=value_ecg_hr_inactive).add_entry(hr_inactive_miscentry)
unisens.save()

There I get an error --> AttributeError: 'MiscEntry' object has no attribute 'key'

Can you explain me the correct code to adding new custom attributes by keeping the old custom attributes?

Thanks, Josua

skjerns commented 3 years ago

The following code works for me

u = unisens.Unisens('example1')
c = unisens.CustomAttributes(key='ecg_hy_inactive', value=101.0)
u.add_entry(c)
u.save()

If you do not want to overwrite the existing customAttributes, you need to access the already existing one and add it to there, else it will be overwritten. You can also access attributes with generic Python syntax

u = unisens.Unisens('z:/example1')
c = unisens.CustomAttributes(key='key1', value='value1')
u.add_entry(c)
u.save()

u = unisens.Unisens('z:/example1')
u.customAttributes.key2 = 'value2' # uses generic Python syntax
u.save()

u = unisens.Unisens('z:/example1')
print(u.customAttributes)
#<customAttributes({'key1': 'value1', 'key2': 'value2'})>
JoshM94 commented 3 years ago

I'm not sure if this is what you meant. But this worked great for me. Only the new parameter is added, the old parameters still exist in the unisens file.

u = Unisens('C:/Users/Josua/Desktop/example1')

value = 100
u.CustomAttributes.new_key = value
u.save()
skjerns commented 3 years ago

perfect, so it solved your problem?

JoshM94 commented 3 years ago

Yes, thanks for your help.