brendanjmeade / celeri

Next generation earthquake cycle kinematics
BSD 3-Clause "New" or "Revised" License
24 stars 6 forks source link

Understand why I have to return blocks when I rinclude the 6 lines below #27

Closed brendanjmeade closed 2 years ago

brendanjmeade commented 2 years ago

https://github.com/brendanjmeade/celeri/blob/eaf6f28dccedad5535b37ad88ccdcbd8d640f1ba/celeri.py#L469-L469

brendanjmeade commented 2 years ago
# This works...but...I have to return blocks to get the changes to propagate back to the celeri.ipynb namespace???
# These two lines reoder the rows of blocks so that the block with label zero is not index 0
# and the block labels then increase sequentially.  I copied this from the bottom of:
# https://stackoverflow.com/questions/39992502/rearrange-rows-of-pandas-dataframe-based-on-list-and-keeping-the-order
# and I definitely don't understand it but emperically it seems to work.
block = (
    block.set_index(block.block_label, append=True)
    .sort_index(level=1)
    .reset_index(1, drop=True)
)
block = block.reset_index()
block = block.loc[:, ~block.columns.str.match("index")]
brendanjmeade commented 2 years ago

I understand this now. I need to explicitly return blocks here because it was being reassigned (blocks = NNN) within the function. Removed comments in commit: https://github.com/brendanjmeade/celeri/commit/d0ff1b13fc46b85ab58c89f6f57b393c0e0b170b

tbenthompson commented 2 years ago

Yeah, it's the distinction between mutating an object and creating a new object and assigning it to the same name. The first two answers here might be useful: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference

brendanjmeade commented 2 years ago

Thanks for the link. This bit, "If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object." helps a lot. It's great to be learning so much!