# synthesize_profiles

Run:
python3 main_synthesize_profile.py

To avoid warning run: 

Python script to synthesize snow stratigraphy per timestamp from modeled SNOWPACK *.pro-files (see https://www.slf.ch/de/services-und-produkte/snowpack.html for more details).

1) Read *.pro -file
2) Run RF model instability to detect weak layer and compute probability of beig unstable for each layer according to Mayer et al., 2022 (https://doi.org/10.5194/tc-16-4593-2022)
3) Synthesize snow stratigraphy for each timestamp:
    - Liquid water content and mean snow temperature for different snow depths (Upper 10cm, upper 20cm, whole profile)
    - weak layer stability paramters, i.e. probability unstable, sn38, ssi, sk38 for 2 layers:      
        - weak layer detected by Rf model instability     
        - lowest layer within penetration depth
    - weak layer and slab properties for weak layer detected by Rf model instability
        - weak layer variables: e.g. grain size, grain type, critical cut length (Richter et al., 2019; https://doi.org/10.5194/tc-13-3353-2019), density, liquid water content,...
        - slab properties: e.g. mean density, mean liquid water content, mean grain size, mean hand harndess, ...
4) Generate pandas dataframe of synthesized variables per timestamp.
5) Write dataframe to csv


calls Function get_synthesized_stratigraphy_variables.loadProfile. Optional variables are:
def loadProfile(filename, 
                a = datetime.datetime(2021, 10, 1, 12), b = datetime.datetime(2022, 6, 30, 12), 
                daily=False, 
                write_df=False, 
                filename_output = './test.csv',
                structure_depths = [10,20], structure_variables = ['lwc','temperature'],
                nwl=1, deepestwl=False, addallwlinfo = False, penetration_depth_properties = True):
    '''
    filename: str
        filename of *.pro file to sythesize and extract computed variables.
    a: datetime object
        profiles will be sythesized between two dates a and b
        a is starting date
        Default: a = datetime.datetime(2021, 10, 1, 12)
    b: datetime object
        profiles will be sythesized between two dates a and b
        b is end date
        Default: b = datetime.datetime(2022, 6, 30, 12)
    daily: boolean
        if False: each timestamp, which is available in profile will be synthesized.
        if True: Only one profile perday will be extracted and synthesized.
        Default: False
    write_df: boolean
        if False: No csv-file will be witten.
        if True: csv file will be written, recommended
        Default: True
    filename_output: str
        Name of csv file in which synthesized variables should be written
        Default: filename_output = './test.csv'
    
    For each timestamp, the profile is synthesized and following variables are extracted:
    ----------------------------------
    hs: snow depth [cm]
    lwc_all: weighted average of liquid water content by volume of whole snowpack [%]
    temperature_all: weighted average of snow temperature of whole snowpack [°C]
    swe_all: snow water equivalent [kg/m^2]
    density_all: average density of snowpack [kg/m^3]
    hardness_all: weigthed average of hand hardness of snowpack
    perc_pers_all: Percentage of persistant layers in profile (faceted crystals, depth hoar, surface hoar, rounded facets) 
        computed as: sum(thickness of persistent layers) / sum(thickness)
    perc_crust_all: Percentage of crusts in profile
    
    Additional default variables are:
    ---------------------------------
    temperature_10, temperature_20 [in °C], lwc_10, lwc_20 [in %], 
    other structure variables: perc_pers, pers_crust, density, swe, hand_hardness of certain depths
    These variables are computed as the weighted average of the upper x cm of the snowpack ( sum(variable*thickness) / sum(thickness) )
    e.g. _10 are the upper 10 cm, _20 are the upper 20 cm
    
    Add other additional variable:
    ------------------------------
    structure_variables: list
        A list containing variables of which the upper x cm of the snowpack should be averaged
        Add more variables to list if needed.
        Default: structure_variables = ['lwc','temperature']
        If no other information is needed, pass empty list: structure_variables = []
    structure_depths: list
        A list containing the depths of which the upper x cm in list should be averaged for each of the variables above.
        Add more depths to list if needed.
        Default: structure_depths = [10,20]
        Insteresting variables could also be: structure_depths = [10,20,50,100]
        If no other information is needed, pass empty list: structure_depths = []
    nwl: int
        Number of weak layers, which will be written out.
        All weak and slab layer variables are calculated for the weak layer, which was detected by Stephie's RF model
        All weak layer and slab layer properties will be named wl1_, wl_2, wl..._ , sl1_, sl2_, sl..._
        Weak layers are found by searching for extremas in P_unstable.
        Weak layer are sorted by stability, most unstable (highest value of P_unstable - Probability of being unstable) will be wl1
        If no extrema (or second, third extrema,...) is found, weak and slab layer properties will be assigned to the values of the deepest layer in the profile
        Default: nwl=1
        Properties of weak layer x, which will be written are:
            wlx_st_pinst: weak layer probability of being unstable (in stephie's paper for pmax>0.77 the snowpack is unstable) [0-1]
            wlx_st_sn38: SN38 weak layer natural stability index projected on 38° slope [0-1]
            wlx_st_ssi: SSI weak layer strucural stability index [0-1] ?
            wlx_st_sk38: SK38 weak layer skier stability index projected on 38° slope [0-1]
            wlx_rc: weak layer critical cut length [cm] (one of stephie's features, flat field parameterization works better than slope one)
            slx_depth: slab thickness [cm]
    deepestwl: Bool
        Default: False
        If true, properties of the deepest weak layer with pinst>0.77 will be extracted.
        If no value >0.77 then same layer as wl1 will be used, otherwise deepest layer
    addallwlinfo: Bool
        Default: False
        If true following additional weak and slab layer properties will be extracted for all weak layers:
            wlx_density: weak layer density [kg/m^3]
            wlx_viscdefrate: weak layer viscous deformation rate (one of stephie's features)
            wlx_sphericity: weak layer sphericity [0-1, with 1 being fully spherical and 0 being fully faceted]  (one of stephie's features)
            wlx_grain_type: first grain type of weak layer
            wlx_grainsize: weak layer graon syze [mm] (one of stephie's features)
            wlx_hand_hardness: weak layer hand hardness [1-5, 1: fist; 2: 4fingers; 3: 1finger; 4: pencil; 5: knife]
            wlx_lwc: weak layer liquid water content by volume [%]
            slx_hand_hardness: weighted average of slab hand hardness [1-5]
            slx_density: weighted average of slab density [kg/m^3]
            slx_grainsize: weighted average of slab grain size [mm?]
            slx_lwc: weighted average of slab liquid water content by volume [%]
            slx_temperature: weighted average of slab temperature [°C]
    penetration_depth_properties: Bool
        Default: True
        Following parameters will be extracted:
            penetrationdepth: Penetration depth in cm! Attention: SNOWPACK computes penetration depth in meters! (one of Stephie's features) [cm] 
            pd_rc: Critical cut length for the last layer which will be penetrated (penetration depth wl) HS - penetration depth) [cm]
            pd_st_pinst: probability of being unstable for the penetration depth wl [0-1, > 0.77 is unstable]
            pd_st_sn38: SN38 for penetration depth wl
            pd_st_ssi: SSI for penetration depth wl
            pd_st_sk38: SK38 for penetration depth wl
    '''

## Getting started

To make it easy for you to get started with GitLab, here's a list of recommended next steps.

Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!

## Add your files

- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:

```
cd existing_repo
git remote add origin https://gitlabext.wsl.ch/richter/ccamm_avalanche_forecasting.git
git branch -M main
git push -uf origin main
```

## Integrate with your tools

- [ ] [Set up project integrations](https://gitlabext.wsl.ch/richter/ccamm_avalanche_forecasting/-/settings/integrations)

## Collaborate with your team

- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)

## Test and Deploy

Use the built-in continuous integration in GitLab.

- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)

***

# Editing this README

When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.

## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.

## Name
Choose a self-explaining name for your project.

## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.

## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.

## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.

## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.

## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.

## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.

## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.

## Contributing
State if you are open to contributions and what your requirements are for accepting them.

For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.

You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.

## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.

## License
For open source projects, say how it is licensed.

## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
