Creating random weighted probability fragility function

Hi there,

I’m still new to riskscape/coding and was wondering if anyone had any ideas on how to get around some errors I’m encountering. I’m trying to create a random weighted probability fragility function but I’m having some issues with my code. I’ve attached the error I’m coming across and my fragility code. Any feedback would be greatly appreciated!

Cheers,
Jess


Hi Jess,

So I think the problem here is you are mixing the old and new styles of defining a Python function in RiskScape.

The old style defines the RETURN_TYPE and ARGUMENT_TYPES inline in the Python code. This approach is limited - it only works for Jython (the default Python that RiskScape uses) and not CPython (“regular” Python to most people). We prefer to phase out this old approach, so we don’t really document it in examples any more.

The new style of defining a function is the [function Manhole_Fragility] section in your project.ini file. All you need to do to make your function work is change the last line to match your return-type, i.e.

return-type = struct(DS_1: floating, DS_2: floating, DS_3: floating, DS: integer) 

When both the old and new styles are present, RiskScape ignores the old style. So in your Python code, you could just delete the lines between ID = ... and RETURN_TYPE = ... to avoid confusion.

Finally, if you’re want to use weighted random probability, then it might be helpful to switch to CPython. You can use regular Python packages like numpy (and can google ‘how do I do XYZ in Python’ more easily). To use CPython, you will need Python 3 installed on your system. There’s some setup instructions for RiskScape here:
https://riskscape.org.nz/docs/reference/functions/cpython.html#configuring-cpython-support-in-riskscape

Unfortunately, switching to CPython would mean rewriting most of your code. There’s a CPython example function that does a very similar thing with a log normal CDF fragility function (using scipy) here:
https://riskscape.org.nz/docs/intermediate/modelling.html#cpython

Hope that helps.

Tim

Thank you Tim! Got it all working now. That was super helpful!

Have a great day,
Jess

Kia ora Jess

If you ended up using cPython, there is a super useful function in numpy that allows you to randomly sample a list (e.g. damage states) with probabilities.

https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html

If you get the probability of being in each DS from your fragility curves (and then calculating the probability of being IN each DS) you can then do something like this below where p=[ list of damage state probabilities] .

import numpy
randomDS = numpy.random.choice([‘DS0’, ‘DS1’, ‘DS2’, ‘DS3’], 1, p=[0.1, 0.5, 0.2, 0.2])[0]

Awesome, thank you Nick, that resource will be super helpful in the future!

Thanks again,
Jess :grinning: