swmmio icon indicating copy to clipboard operation
swmmio copied to clipboard

Error writing CURVES section - with workaround

Open MortenGrum opened this issue 1 year ago • 0 comments

The following code leads to incorrect curves data and subsequent errors when loading into SWMM5 (Note: even without modifying the curve data):

model = swmmio.Model("original.inp")
curves = model.inp.curves
model.inp.curves = curves
model.inp.save("new.inp")

Is this a bug?

I managed to find a workaround involving overwriting the write_inp_section method (in swmmio/version_control)/utils.py) as follows:

def override_write_inp_section():
    # Import write_inp_section
    from swmmio.version_control.utils import write_inp_section

    # Copy the original method to a new variable
    write_inp_section_orig = write_inp_section

    # Create a new method that will be used instead of the original
    def _write_inp_section_new(file_object, allheaders, sectionheader, section_data, pad_top=True, na_fill=''):
        if sectionheader == '[CURVES]':
            if not section_data.empty:
                if pad_top:
                    file_object.write('\n\n' + sectionheader + '\n')  # add SWMM-friendly header e.g. [DWF]
                else:
                    file_object.write(sectionheader + '\n')

                # Add custom code for CURVES
                index_as_frame = section_data.index.to_frame()
                index_as_frame.fillna('', inplace=True)
                section_data.index = pd.MultiIndex.from_frame(index_as_frame)

                def name_formatter(name_value):
                    return name_value

                def type_formatter(type_value):
                    return type_value

                objectformatter = {}
                objectformatter['Name'] = name_formatter
                objectformatter['Type'] = type_formatter
                for hedr in section_data.columns:
                    objectformatter[hedr] = ' {{:<{}}}'.format(section_data[hedr].apply(str).str.len().max()).format

                section_data.reset_index(inplace=True)
                section_data_as_string = section_data.to_string(header=False, index=False, formatters=objectformatter)

                file_object.write(section_data_as_string + '\n\n')
        else:
            # Call the original function for other section headers
            write_inp_section_orig(file_object, allheaders, sectionheader, section_data, pad_top, na_fill)

    # Replace the original method with the new one
    swmmio.version_control.utils.write_inp_section = _write_inp_section_new

It's not beautiful and might not handle all cases, but it worked for the curves in my inp.

I hope this might be helpful.

MortenGrum avatar Apr 07 '23 10:04 MortenGrum