How to use element method in root

Best JavaScript code snippet using root

lake_pond_expansion.py

Source:lake_pond_expansion.py Github

copy

Full Screen

1import numpy as np2import gdal, os, sys, glob, random3import pylab as pl4from decimal import *5getcontext().prec = 4 # Set a new precision6def lake_pond_expansion(self, element):7 """8 If a lake or pond exists in an element, expand it by the prescribed rate.9 There is a corresponding reduction in land area to all cohorts following10 expansion.11 """12 13 ##########################################################################################14 # LAKES 15 ##########################################################################################16 ATTM_Lake_Total = self.ATTM_LargeLakes_WT_Y[element] + self.ATTM_LargeLakes_WT_M[element] + \17 self.ATTM_LargeLakes_WT_M[element] + self.ATTM_MediumLakes_WT_Y[element] + \18 self.ATTM_MediumLakes_WT_M[element] + self.ATTM_MediumLakes_WT_O[element] + \19 self.ATTM_SmallLakes_WT_Y[element] + self.ATTM_SmallLakes_WT_M[element] + \20 self.ATTM_SmallLakes_WT_O[element]21 22 #if self.ATTM_Lakes[element] > 0.0 and self.ATTM_Lakes[element] < 1.0 :23 if ATTM_Lake_Total > 0.0 and ATTM_Lake_Total < 1.0 :24 # --------------------------------------------------25 # Determine the fractional amount of lake expansion26 # --------------------------------------------------27 if self.climate_expansion_lakes[element] == 1.0:28 #lake_fraction_increase = self.ATTM_Lakes[element] * self.LakePond['Lake_Expansion'] * 2.029 largelake_wt_y_increase = self.ATTM_LargeLakes_WT_Y[element] * \30 self.LakePond['LargeLake_WT_Y_Expansion'] * 2.031 largelake_wt_m_increase = self.ATTM_LargeLakes_WT_M[element] * \32 self.LakePond['LargeLake_WT_M_Expansion'] * 2.033 largelake_wt_o_increase = self.ATTM_LargeLakes_WT_O[element] * \34 self.LakePond['LargeLake_WT_O_Expansion'] * 2.035 mediumlake_wt_y_increase = self.ATTM_MediumLakes_WT_Y[element] * \36 self.LakePond['MediumLake_WT_Y_Expansion'] * 2.037 mediumlake_wt_m_increase = self.ATTM_MediumLakes_WT_M[element] * \38 self.LakePond['MediumLake_WT_M_Expansion'] * 2.039 mediumlake_wt_o_increase = self.ATTM_MediumLakes_WT_O[element] * \40 self.LakePond['MediumLake_WT_O_Expansion'] * 2.041 smalllake_wt_y_increase = self.ATTM_SmallLakes_WT_Y[element] * \42 self.LakePond['SmallLake_WT_Y_Expansion'] * 2.043 smalllake_wt_m_increase = self.ATTM_SmallLakes_WT_M[element] * \44 self.LakePond['SmallLake_WT_M_Expansion'] * 2.045 smalllake_wt_o_increase = self.ATTM_SmallLakes_WT_O[element] * \46 self.LakePond['SmallLake_WT_O_Expansion'] * 2.047 48 self.climate_expansion_lakes[element] = 0.049 else:50 largelake_wt_y_increase = self.ATTM_LargeLakes_WT_Y[element] * \51 self.LakePond['LargeLake_WT_Y_Expansion'] 52 largelake_wt_m_increase = self.ATTM_LargeLakes_WT_M[element] * \53 self.LakePond['LargeLake_WT_M_Expansion'] 54 largelake_wt_o_increase = self.ATTM_LargeLakes_WT_O[element] * \55 self.LakePond['LargeLake_WT_O_Expansion'] 56 mediumlake_wt_y_increase = self.ATTM_MediumLakes_WT_Y[element] * \57 self.LakePond['MediumLake_WT_Y_Expansion']58 mediumlake_wt_m_increase = self.ATTM_MediumLakes_WT_M[element] * \59 self.LakePond['MediumLake_WT_M_Expansion']60 mediumlake_wt_o_increase = self.ATTM_MediumLakes_WT_O[element] * \61 self.LakePond['MediumLake_WT_O_Expansion']62 smalllake_wt_y_increase = self.ATTM_SmallLakes_WT_Y[element] * \63 self.LakePond['SmallLake_WT_Y_Expansion'] 64 smalllake_wt_m_increase = self.ATTM_SmallLakes_WT_M[element] * \65 self.LakePond['SmallLake_WT_M_Expansion'] 66 smalllake_wt_o_increase = self.ATTM_SmallLakes_WT_O[element] * \67 self.LakePond['SmallLake_WT_O_Expansion']68 lake_fraction_increase = largelake_wt_y_increase + largelake_wt_m_increase + \69 largelake_wt_o_increase + mediumlake_wt_y_increase + \70 mediumlake_wt_m_increase + mediumlake_wt_o_increase + \71 smalllake_wt_y_increase + smalllake_wt_m_increase + \72 smalllake_wt_o_increase73 74 # land_available = self.ATTM_Wet_NPG[element] + self.ATTM_Wet_LCP[element] + \75 # self.ATTM_Wet_CLC[element] + self.ATTM_Wet_FCP[element] + \76 # self.ATTM_Wet_HCP[element] + self.ATTM_Gra_NPG[element] + \77 # self.ATTM_Gra_LCP[element] + self.ATTM_Gra_FCP[element] + \78 # self.ATTM_Gra_HCP[element] + self.ATTM_Shr_NPG[element] + \79 # self.ATTM_Shr_LCP[element] + self.ATTM_Shr_FCP[element] + \80 # self.ATTM_Shr_HCP[element]81 land_available = self.ATTM_CLC_WT_Y[element] + self.ATTM_CLC_WT_M[element] + \82 self.ATTM_CLC_WT_O[element] + self.ATTM_CoastalWaters_WT_O[element] + \83 self.ATTM_DrainedSlope_WT_Y[element] + self.ATTM_DrainedSlope_WT_M[element] + \84 self.ATTM_DrainedSlope_WT_O[element] + self.ATTM_FCP_WT_Y[element] + \85 self.ATTM_FCP_WT_M[element] + self.ATTM_FCP_WT_O[element] + \86 self.ATTM_HCP_WT_Y[element] + self.ATTM_HCP_WT_M[element] + \87 self.ATTM_HCP_WT_O[element] + self.ATTM_LCP_WT_Y[element] + \88 self.ATTM_LCP_WT_M[element] + self.ATTM_LCP_WT_O[element] + \89 self.ATTM_Meadow_WT_Y[element] + self.ATTM_Meadow_WT_M[element] + \90 self.ATTM_Meadow_WT_O[element] + self.ATTM_NoData_WT_O[element] + \91 self.ATTM_SandDunes_WT_Y[element] + self.ATTM_SandDunes_WT_M[element] + \92 self.ATTM_SandDunes_WT_O[element] + self.ATTM_SaturatedBarrens_WT_Y[element] + \93 self.ATTM_SaturatedBarrens_WT_M[element] + self.ATTM_SaturatedBarrens_WT_O[element] + \94 self.ATTM_Shrubs_WT_O[element]95 96 # ==================================================================================97 # Case 0:98 # The sum of the fractional lake area + lake_fraction_increase >= the available99 # land available for pond expansion (not expanding into rivers, urban, lakes).100 #101 # In this case, the fractional lake area is equal to the total amount of land102 # cohorts and all the land cohorts are set to 0.0103 # ==================================================================================104 if lake_fraction_increase >= land_available:105 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -106 self.ATTM_LargeLakes_WT_Y[element] = self.ATTM_LargeLakes_WT_Y[element] + \107 ((self.ATTM_LargeLakes_WT_Y[element] / ATTM_Lake_Total) * land_available)108 self.ATTM_LargeLakes_WT_M[element] = self.ATTM_LargeLakes_WT_M[element] + \109 ((self.ATTM_LargeLakes_WT_M[element] / ATTM_Lake_Total) * land_available)110 self.ATTM_LargeLakes_WT_O[element] = self.ATTM_LargeLakes_WT_O[element] + \111 ((self.ATTM_LargeLakes_WT_O[element] / ATTM_Lake_Total) * land_available)112 self.ATTM_MediumLakes_WT_Y[element] = self.ATTM_MediumLakes_WT_Y[element] + \113 ((self.ATTM_MediumLakes_WT_Y[element] / ATTM_Lake_Total) * land_available)114 self.ATTM_MediumLakes_WT_M[element] = self.ATTM_MediumLakes_WT_M[element] + \115 ((self.ATTM_MediumLakes_WT_M[element] / ATTM_Lake_Total) * land_available)116 self.ATTM_MediumLakes_WT_O[element] = self.ATTM_MediumLakes_WT_O[element] + \117 ((self.ATTM_MediumLakes_WT_O[element] / ATTM_Lake_Total) * land_available)118 self.ATTM_SmallLakes_WT_Y[element] = self.ATTM_SmallLakes_WT_Y[element] + \119 ((self.ATTM_SmallLakes_WT_Y[element] / ATTM_Lake_Total) * land_available)120 self.ATTM_SmallLakes_WT_M[element] = self.ATTM_SmallLakes_WT_M[element] + \121 ((self.ATTM_SmallLakes_WT_M[element] / ATTM_Lake_Total) * land_available)122 self.ATTM_SmallLakes_WT_O[element] = self.ATTM_SmallLakes_WT_O[element] + \123 ((self.ATTM_SmallLakes_WT_O[element] / ATTM_Lake_Total) * land_available)124 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -125 self.ATTM_CLC_WT_Y[element] = 0.0126# if 'CLC_WT_Y' in self.land_cohorts[element]:127# self.land_cohorts[element].remove('CLC_WT_Y')128 self.ATTM_CLC_WT_M[element] = 0.0129# if 'CLC_WT_M' in self.land_cohorts[element]:130# self.land_cohorts[element].remove('CLC_WT_M')131 132 self.ATTM_CLC_WT_O[element] = 0.0133# if 'CLC_WT_O' in self.land_cohorts[element]:134# self.land_cohorts[element].remove('CLC_WT_O')135 self.ATTM_DrainedSlope_WT_Y[element] = 0.0136# if 'DrainedSlope_WT_Y' in self.land_cohorts[element]:137# self.land_cohorts[element].remove('DrainedSlope_WT_Y')138 self.ATTM_DrainedSlope_WT_M[element] = 0.0139# if 'DrainedSlope_WT_M' in self.land_cohorts[element]:140# self.land_cohorts[element].remove('DrainedSlope_WT_M')141 self.ATTM_DrainedSlope_WT_O[element] = 0.0142# if 'DrainedSlope_WT_O' in self.land_cohorts[element]:143# self.land_cohorts[element].remove('DrainedSlope_WT_O')144 self.ATTM_FCP_WT_Y[element] = 0.0145# if 'FCP_WT_Y' in self.land_cohorts[element]:146# self.land_cohorts[element].remove('FCP_WT_Y')147 self.ATTM_FCP_WT_M[element] = 0.0148# if 'FCP_WT_M' in self.land_cohorts[element]:149# self.land_cohorts[element].remove('FCP_WT_O')150 self.ATTM_HCP_WT_Y[element] = 0.0151# if 'HCP_WT_Y' in self.land_cohorts[element]:152# self.land_cohorts[element].remove('HCP_WT_Y')153 self.ATTM_HCP_WT_M[element] = 0.0154# if 'HCP_WT_M' in self.land_cohorts[element]:155# self.land_cohorts[element].remove('HCP_WT_M')156 self.ATTM_HCP_WT_O[element] = 0.0157# if 'HCP_WT_O' in self.land_cohorts[element]:158# self.land_cohorts[element].remove('HCP_WT_O')159 self.ATTM_LCP_WT_Y[element] = 0.0160# if 'LCP_WT_Y' in self.land_cohorts[element]:161# self.land_cohorts[element].remove('LCP_WT_Y')162 self.ATTM_LCP_WT_M[element] = 0.0163# if 'LCP_WT_M' in self.land_cohorts[element]:164# self.land_cohorts[element].remove('LCP_WT_M')165 self.ATTM_LCP_WT_O[element] = 0.0166# if 'LCP_WT_O' in self.land_cohorts[element]:167# self.land_cohorts[element].remove('LCP_WT_O')168 self.ATTM_Meadow_WT_Y[element] = 0.0169# if 'Meadow_WT_Y' in self.land_cohorts[element]:170# self.land_cohorts[element].remove('Meadow_WT_Y')171 self.ATTM_Meadow_WT_M[element] = 0.0172# if 'Meadow_WT_M' in self.land_cohorts[element]:173# self.land_cohorts[element].remove('Meadow_WT_M')174 self.ATTM_Meadow_WT_O[element] = 0.0175# if 'Meadow_WT_O' in self.land_cohorts[element]:176# self.land_cohorts[element].remove('Meadow_WT_O')177 self.ATTM_SandDunes_WT_Y[element] = 0.0178# if 'SandDunes_WT_Y' in self.land_cohort[element]:179# self.land_cohorts[element].remove('SandDunes_WT_Y')180 self.ATTM_SandDunes_WT_M[element] = 0.0181# if 'SandDunes_WT_M' in self.land_cohorts[element]:182# self.land_cohorts[element].remove('SandDunes_WT_M')183 self.ATTM_SandDunes_WT_O[element] = 0.0184# if 'SandDunes_WT_O' in self.land_cohorts[element]:185# self.land_cohorts[element].remove('SandDunes_WT_O')186 self.ATTM_SaturatedBarrens_WT_Y[element] = 0.0187# if 'SaturatedBarrens_WT_Y' in self.land_cohorts[element]:188# self.land_cohorts[element].remove('SaturatedBarrens_WT_Y')189 self.ATTM_SaturatedBarrens_WT_M[element] = 0.0190# if 'SaturatedBarrens_WT_M' in self.land_cohorts[element]:191# self.land_cohorts[element].remove('SaturatedBarrens_WT_M')192 self.ATTM_SaturatedBarrens_WT_O[element] = 0.0193# if 'SaturatedBarrens_WT_O' in self.land_cohorts[element]:194# self.land_cohorts[element].remove('SaturatedBarrens_WT_O')195 self.ATTM_Shrubs_WT_O[element] = 0.0196# if 'Shrubs_WT_O' in self.land_cohorts[element]:197# self.land_cohorts[element].remove('Shrubs_WT_O')198 self.ATTM_NoData_WT_O[element] = 0.0199# if 'NoData_WT_O' in self.land_cohorts[element]:200# self.land_cohorts[element].remove('NoData_WT_O')201 202# self.ATTM_Wet_NPG[element] = 0.0203# if 'Wet_NPG' in self.land_cohorts[element]:204# self.land_cohorts[element].remove('Wet_NPG')205# self.ATTM_Wet_LCP[element] = 0.0206# if 'Wet_LCP' in self.land_cohorts[element]:207# self.land_cohorts[element].remove('Wet_LCP')208# self.ATTM_Wet_CLC[element] = 0.0209# if 'Wet_CLC' in self.land_cohorts[element]:210# self.land_cohorts[element].remove('Wet_CLC')211# self.ATTM_Wet_FCP[element] = 0.0212# if 'Wet_FCP' in self.land_cohorts[element]:213# self.land_cohorts[element].remove('Wet_FCP')214# self.ATTM_Wet_HCP[element] = 0.0215# if 'Wet_HCP' in self.land_cohorts[element]:216# self.land_cohorts[element].remove('Wet_HCP')217# self.ATTM_Gra_NPG[element] = 0.0218# if 'Gra_NPG' in self.land_cohorts[element]:219# self.land_cohorts[element].remove('Gra_NPG')220# self.ATTM_Gra_LCP[element] = 0.0221# if 'Gra_LCP' in self.land_cohorts[element]:222# self.land_cohorts[element].remove('Gra_LCP')223# self.ATTM_Gra_FCP[element] = 0.0224# if 'Gra_FCP' in self.land_cohorts[element]:225# self.land_cohorts[element].remove('Gra_FCP')226# self.ATTM_Gra_HCP[element] = 0.0227# if 'Gra_HCP' in self.land_cohorts[element]:228# self.land_cohorts[element].remove('Gra_HCP')229# self.ATTM_Shr_NPG[element] = 0.0230# if 'Shr_NPG' in self.land_cohorts[element]:231# self.land_cohorts[element].remove('Shr_NPG')232# self.ATTM_Shr_LCP[element] = 0.0233# if 'Shr_LCP' in self.land_cohorts[element]:234# self.land_cohorts[element].remove('Shr_LCP')235# self.ATTM_Shr_FCP[element] = 0.0236# if 'Shr_FCP' in self.land_cohorts[element]:237# self.land_cohorts[element].remove('Shr_FCP')238# self.ATTM_Shr_HCP[element] = 0.0239# if 'Shr_HCP' in self.land_cohorts[element]:240# self.land_cohorts[element].remove('Shr_HCP')241 242 # ==================================================================================243 # Case 1:244 # The sum of all the land cohorts exceeds the fractional amount of lake245 # area increase. However, one or more of the land cohorts has a fractional area246 # less than (or equal to) the lake_proportional_reduction value. In this case,247 # the land cohort(s) with the fractional areas less than the lake_proportional_area248 # are reduced to zero and the excess expansion is carried by the remaining cohorts.249 #250 # This case may result in a cascading reduction of cohorts. For example, if on the251 # first pass one land cohort is zeroed out, the remaining fractional reduction added252 # to the remaining cohorts may result in a lake_proportional_area being greater than253 # one of the remaining land cohorts. In this case, the 2nd cohort will need to be254 # zeroed out and the remaining lake area expansion is passed on to the remaining255 # land cohorts.256 # -----------------------------------------------------------------------------------257# elif len(self.land_cohorts[element]) == 0.0: #### 11 Oct 2016. I can't remember what this does!258# #### Or why this is included259# #self.ATTM_Lakes[element] = self.ATTM_Lakes[element]260# self.ATTM_LargeLakes_WT_Y[element] = self.ATTM_LargeLakes_WT_Y[element]261# self.ATTM_LargeLakes_WT_M[element] = self.ATTM_LargeLakes_WT_M[element]262# self.ATTM_LargeLakes_WT_O[element] = self.ATTM_LargeLakes_WT_O[element]263# self.ATTM_MediumLakes_WT_Y[element] = self.ATTM_MediumLakes_WT_Y[element]264# self.ATTM_MediumLakes_WT_M[element] = self.ATTM_MediumLakes_WT_M[element]265# self.ATTM_MediumLakes_WT_O[element] = self.ATTM_MediumLakes_WT_O[element]266# self.ATTM_SmallLakes_WT_Y[element] = self.ATTM_SmallLakes_WT_Y[element]267# self.ATTM_SmallLakes_WT_M[element] = self.ATTM_SmallLakes_WT_M[element]268# self.ATTM_SmallLakes_WT_O[element] = self.ATTM_SmallLakes_WT_O[element]269 270 else: # land_available > lake_fraction_increase:271 #self.ATTM_Lakes[element] = self.ATTM_Lakes[element] + lake_fraction_increase272 self.ATTM_LargeLakes_WT_Y[element] = self.ATTM_LargeLakes_WT_Y[element] + largelake_wt_y_increase273 self.ATTM_LargeLakes_WT_M[element] = self.ATTM_LargeLakes_WT_M[element] + largelake_wt_m_increase274 self.ATTM_LargeLakes_WT_O[element] = self.ATTM_LargeLakes_WT_O[element] + largelake_wt_o_increase275 self.ATTM_MediumLakes_WT_Y[element] = self.ATTM_MediumLakes_WT_Y[element] + mediumlake_wt_y_increase276 self.ATTM_MediumLakes_WT_M[element] = self.ATTM_MediumLakes_WT_M[element] + mediumlake_wt_m_increase277 self.ATTM_MediumLakes_WT_O[element] = self.ATTM_MediumLakes_WT_O[element] + mediumlake_wt_o_increase278 self.ATTM_SmallLakes_WT_Y[element] = self.ATTM_SmallLakes_WT_Y[element] + smalllake_wt_y_increase279 self.ATTM_SmallLakes_WT_M[element] = self.ATTM_SmallLakes_WT_M[element] + smalllake_wt_m_increase280 self.ATTM_SmallLakes_WT_O[element] = self.ATTM_SmallLakes_WT_O[element] + smalllake_wt_o_increase281 282# cohort_reduction = lake_fraction_increase / len(self.land_cohorts[element])283 # -------------------------------------284 # Reduce all appropriate land cohorts285 # -------------------------------------286 not_enough_land = 0.0287 not_enough_land_count = 0.0288 land_count = 0.0289 lake_count = 0.0290 # Determine land cohorts available for reduction in element291 if self.ATTM_CLC_WT_Y[element] > 0.0: land_count = land_count + 1292 if self.ATTM_CLC_WT_M[element] > 0.0: land_count = land_count + 1293 if self.ATTM_CLC_WT_O[element] > 0.0: land_count = land_count + 1294 if self.ATTM_CoastalWaters_WT_O[element] > 0.0 : land_count = land_count + 1295 if self.ATTM_DrainedSlope_WT_Y[element] > 0.0 : land_count = land_count + 1296 if self.ATTM_DrainedSlope_WT_M[element] > 0.0 : land_count = land_count + 1297 if self.ATTM_DrainedSlope_WT_O[element] > 0.0 : land_count = land_count + 1298 if self.ATTM_FCP_WT_Y[element] > 0.0 : land_count = land_count + 1299 if self.ATTM_FCP_WT_M[element] > 0.0 : land_count = land_count + 1300 if self.ATTM_FCP_WT_O[element] > 0.0 : land_count = land_count + 1301 if self.ATTM_HCP_WT_Y[element] > 0.0 : land_count = land_count + 1302 if self.ATTM_HCP_WT_M[element] > 0.0 : land_count = land_count + 1303 if self.ATTM_HCP_WT_O[element] > 0.0 : land_count = land_count + 1304 if self.ATTM_LCP_WT_Y[element] > 0.0 : land_count = land_count + 1305 if self.ATTM_LCP_WT_M[element] > 0.0 : land_count = land_count + 1306 if self.ATTM_LCP_WT_O[element] > 0.0 : land_count = land_count + 1307 if self.ATTM_Meadow_WT_Y[element] > 0.0 : land_count = land_count + 1308 if self.ATTM_Meadow_WT_M[element] > 0.0 : land_count = land_count + 1309 if self.ATTM_Meadow_WT_O[element] > 0.0 : land_count = land_count + 1310 if self.ATTM_NoData_WT_O[element] > 0.0 : land_count = land_count + 1311 if self.ATTM_SandDunes_WT_Y[element] > 0.0 : land_count = land_count + 1312 if self.ATTM_SandDunes_WT_M[element] > 0.0 : land_count = land_count + 1313 if self.ATTM_SandDunes_WT_O[element] > 0.0 : land_count = land_count + 1314 if self.ATTM_SaturatedBarrens_WT_Y[element] > 0.0 : land_count = land_count + 1315 if self.ATTM_SaturatedBarrens_WT_M[element] > 0.0 : land_count = land_count + 1316 if self.ATTM_SaturatedBarrens_WT_O[element] > 0.0 : land_count = land_count + 1317 if self.ATTM_Shrubs_WT_O[element] > 0.0 : land_count = land_count + 1318 # Determine proportional reduction for land cohorts present319 cohort_reduction = lake_fraction_increase / land_count320 # Sequence through land cohorts and reduce as appropriate321 if self.ATTM_CLC_WT_Y[element] > 0.0:322 self.ATTM_CLC_WT_Y[element] = self.ATTM_CLC_WT_Y[element] - cohort_reduction323 if self.ATTM_CLC_WT_Y[element] < 0.0:324 not_enough_land = not_enough_land + abs(self.ATTM_CLC_WT_Y[element])325 not_enough_land_count = not_enough_land_count + 1326 self.ATTM_CLC_WT_Y[element] = 0.0327 if self.ATTM_CLC_WT_M[element] > 0.0:328 self.ATTM_CLC_WT_M[element] = self.ATTM_CLC_WT_M[element] - cohort_reduction329 if self.ATTM_CLC_WT_M[element] < 0.0:330 not_enough_land = not_enough_land + abs(self.ATTM_CLC_WT_M[element])331 not_enough_land_count = not_enough_land_count + 1332 self.ATTM_CLC_WT_M[element] = 0.0333 if self.ATTM_CLC_WT_O[element] > 0.0:334 self.ATTM_CLC_WT_O[element] = self.ATTM_CLC_WT_O[element] - cohort_reduction335 if self.ATTM_CLC_WT_O[element] < 0.0:336 not_enough_land = not_enough_land + abs(self.ATTM_CLC_WT_O[element])337 not_enough_land_count = not_enough_land_count + 1338 self.ATTM_CLC_WT_O[element] = 0.0339 if self.ATTM_CoastalWaters_WT_O[element] > 0.0:340 self.ATTM_CoastalWaters_WT_O[element] = self.ATTM_CoastalWaters_WT_O[element] - cohort_reduction341 if self.ATTM_CoastalWaters_WT_O[element] < 0.0:342 not_enough_land = not_enough_land + abs(self.ATTM_CoastalWaters_WT_O[element])343 not_enough_land_count = not_enough_land_count + 1344 self.ATTM_CoastalWaters_WT_O[element] = 0.0 345 if self.ATTM_DrainedSlope_WT_Y[element] > 0.0:346 self.ATTM_DrainedSlope_WT_Y[element] = self.ATTM_DrainedSlope_WT_Y[element] - cohort_reduction347 if self.ATTM_DrainedSlope_WT_Y[element] < 0.0:348 not_enough_land = not_enough_land + abs(self.ATTM_DrainedSlope_WT_Y[element])349 not_enough_land_count = not_enough_land_count + 1350 self.ATTM_DrainedSlope_WT_Y[element] = 0.0351 if self.ATTM_DrainedSlope_WT_M[element] > 0.0:352 self.ATTM_DrainedSlope_WT_M[element] = self.ATTM_DrainedSlope_WT_M[element] - cohort_reduction353 if self.ATTM_DrainedSlope_WT_M[element] < 0.0:354 not_enough_land = not_enough_land + abs(self.ATTM_DrainedSlope_WT_M[element])355 not_enough_land_count = not_enough_land_count + 1356 self.ATTM_DrainedSlope_WT_M[element] = 0.0357 if self.ATTM_DrainedSlope_WT_O[element] > 0.0:358 self.ATTM_DrainedSlope_WT_O[element] = self.ATTM_DrainedSlope_WT_O[element] - cohort_reduction359 if self.ATTM_DrainedSlope_WT_O[element] < 0.0:360 not_enough_land = not_enough_land + abs(self.ATTM_DrainedSlope_WT_O[element])361 not_enough_land_count = not_enough_land_count + 1362 self.ATTM_DrainedSlope_WT_O[element] = 0.0363 if self.ATTM_FCP_WT_Y[element] > 0.0:364 self.ATTM_FCP_WT_Y[element] = self.ATTM_FCP_WT_Y[element] - cohort_reduction365 if self.ATTM_FCP_WT_Y[element] < 0.0:366 not_enough_land = not_enough_land + abs(self.ATTM_FCP_WT_Y[element])367 not_enough_land_count = not_enough_land_count + 1368 self.ATTM_FCP_WT_Y[element] = 0.0369 if self.ATTM_FCP_WT_M[element] > 0.0:370 self.ATTM_FCP_WT_M[element] = self.ATTM_FCP_WT_M[element] - cohort_reduction371 if self.ATTM_FCP_WT_M[element] < 0.0:372 not_enough_land = not_enough_land + abs(self.ATTM_FCP_WT_M[element])373 not_enough_land_count = not_enough_land_count + 1374 self.ATTM_FCP_WT_M[element] = 0.0375 if self.ATTM_FCP_WT_O[element] > 0.0:376 self.ATTM_FCP_WT_O[element] = self.ATTM_FCP_WT_O[element] - cohort_reduction377 if self.ATTM_FCP_WT_O[element] < 0.0:378 not_enough_land = not_enough_land + abs(self.ATTM_FCP_WT_O[element])379 not_enough_land_count = not_enough_land_count + 1380 self.ATTM_FCP_WT_O[element] = 0.0381 if self.ATTM_HCP_WT_Y[element] > 0.0:382 self.ATTM_HCP_WT_Y[element] = self.ATTM_HCP_WT_Y[element] - cohort_reduction383 if self.ATTM_HCP_WT_Y[element] < 0.0:384 not_enough_land = not_enough_land + abs(self.ATTM_HCP_WT_Y[element])385 not_enough_land_count = not_enough_land_count + 1386 self.ATTM_HCP_WT_Y[element] = 0.0387 if self.ATTM_HCP_WT_M[element] > 0.0:388 self.ATTM_HCP_WT_M[element] = self.ATTM_HCP_WT_M[element] - cohort_reduction389 if self.ATTM_HCP_WT_M[element] < 0.0:390 not_enough_land = not_enough_land + abs(self.ATTM_HCP_WT_M[element])391 not_enough_land_count = not_enough_land_count + 1392 self.ATTM_HCP_WT_M[element] = 0.0393 if self.ATTM_HCP_WT_O[element] > 0.0:394 self.ATTM_HCP_WT_O[element] = self.ATTM_HCP_WT_O[element] - cohort_reduction395 if self.ATTM_HCP_WT_O[element] < 0.0:396 not_enough_land = not_enough_land + abs(self.ATTM_HCP_WT_O[element])397 not_enough_land_count = not_enough_land_count + 1398 self.ATTM_HCP_WT_O[element] = 0.0399 if self.ATTM_LCP_WT_Y[element] > 0.0:400 self.ATTM_LCP_WT_Y[element] = self.ATTM_LCP_WT_Y[element] - cohort_reduction401 if self.ATTM_LCP_WT_Y[element] < 0.0:402 not_enough_land = not_enough_land + abs(self.ATTM_LCP_WT_Y[element])403 not_enough_land_count = not_enough_land_count + 1404 self.ATTM_LCP_WT_Y[element] = 0.0405 if self.ATTM_LCP_WT_M[element] > 0.0:406 self.ATTM_LCP_WT_M[element] = self.ATTM_LCP_WT_M[element] - cohort_reduction407 if self.ATTM_LCP_WT_M[element] < 0.0:408 not_enough_land = not_enough_land + abs(self.ATTM_LCP_WT_M[element])409 not_enough_land_count = not_enough_land_count + 1410 self.ATTM_LCP_WT_M[element] = 0.0411 if self.ATTM_LCP_WT_O[element] > 0.0:412 self.ATTM_LCP_WT_O[element] = self.ATTM_LCP_WT_O[element] - cohort_reduction413 if self.ATTM_LCP_WT_O[element] < 0.0:414 not_enough_land = not_enough_land + abs(self.ATTM_LCP_WT_O[element])415 not_enough_land_count = not_enough_land_count + 1416 self.ATTM_LCP_WT_O[element] = 0.0417 if self.ATTM_Meadow_WT_Y[element] > 0.0:418 self.ATTM_Meadow_WT_Y[element] = self.ATTM_Meadow_WT_Y[element] - cohort_reduction419 if self.ATTM_Meadow_WT_Y[element] < 0.0:420 not_enough_land = not_enough_land + abs(self.ATTM_Meadow_WT_Y[element])421 not_enough_land_count = not_enough_land_count + 1422 self.ATTM_Meadow_WT_Y[element] = 0.0423 if self.ATTM_Meadow_WT_M[element] > 0.0:424 self.ATTM_Meadow_WT_M[element] = self.ATTM_Meadow_WT_M[element] - cohort_reduction425 if self.ATTM_Meadow_WT_M[element] < 0.0:426 not_enough_land = not_enough_land + abs(self.ATTM_Meadow_WT_M[element])427 not_enough_land_count = not_enough_land_count + 1428 self.ATTM_Meadow_WT_M[element] = 0.0429 if self.ATTM_Meadow_WT_O[element] > 0.0:430 self.ATTM_Meadow_WT_O[element] = self.ATTM_Meadow_WT_O[element] - cohort_reduction431 if self.ATTM_Meadow_WT_O[element] < 0.0:432 not_enough_land = not_enough_land + abs(self.ATTM_Meadow_WT_O[element])433 not_enough_land_count = not_enough_land_count + 1434 self.ATTM_Meadow_WT_O[element] = 0.0435 if self.ATTM_SandDunes_WT_Y[element] > 0.0:436 self.ATTM_SandDunes_WT_Y[element] = self.ATTM_SandDunes_WT_Y[element] - cohort_reduction437 if self.ATTM_SandDunes_WT_Y[element] < 0.0:438 not_enough_land = not_enough_land + abs(self.ATTM_SandDunes_WT_Y[element])439 not_enough_land_count = not_enough_land_count + 1440 self.ATTM_SandDunes_WT_Y[element] = 0.0441 if self.ATTM_SandDunes_WT_M[element] > 0.0:442 self.ATTM_SandDunes_WT_M[element] = self.ATTM_SandDunes_WT_M[element] - cohort_reduction443 if self.ATTM_SandDunes_WT_M[element] < 0.0:444 not_enough_land = not_enough_land + abs(self.ATTM_SandDunes_WT_M[element])445 not_enough_land_count = not_enough_land_count + 1446 self.ATTM_SandDunes_WT_M[element] = 0.0447 if self.ATTM_SandDunes_WT_O[element] > 0.0:448 self.ATTM_SandDunes_WT_O[element] = self.ATTM_SandDunes_WT_O[element] - cohort_reduction449 if self.ATTM_SandDunes_WT_O[element] < 0.0:450 not_enough_land = not_enough_land + abs(self.ATTM_SandDunes_WT_O[element])451 not_enough_land_count = not_enough_land_count + 1452 self.ATTM_SandDunes_WT_O[element] = 0.0453 if self.ATTM_NoData_WT_O[element] > 0.0:454 self.ATTM_NoData_WT_O[element] = self.ATTM_NoData_WT_O[element] - cohort_reduction455 if self.ATTM_NoData_WT_O[element] < 0.0:456 not_enough_land = not_enough_land + abs(self.ATTM_NoData_WT_O[element])457 not_enough_land_count = not_enough_land_count + 1458 self.ATTM_NoData_WT_O[element] = 0.0459 if self.ATTM_SaturatedBarrens_WT_Y[element] > 0.0:460 self.ATTM_SaturatedBarrens_WT_Y[element] = self.ATTM_SaturatedBarrens_WT_Y[element] - cohort_reduction461 if self.ATTM_SaturatedBarrens_WT_Y[element] < 0.0:462 not_enough_land = not_enough_land + abs(self.ATTM_SaturatedBarrens_WT_Y[element])463 not_enough_land_count = not_enough_land_count + 1464 self.ATTM_SaturatedBarrens_WT_Y[element] = 0.0465 if self.ATTM_SaturatedBarrens_WT_M[element] > 0.0:466 self.ATTM_SaturatedBarrens_WT_M[element] = self.ATTM_SaturatedBarrens_WT_M[element] - cohort_reduction467 if self.ATTM_SaturatedBarrens_WT_M[element] < 0.0:468 not_enough_land = not_enough_land + abs(self.ATTM_SaturatedBarrens_WT_M[element])469 not_enough_land_count = not_enough_land_count + 1470 self.ATTM_SaturatedBarrens_WT_M[element] = 0.0471 if self.ATTM_SaturatedBarrens_WT_O[element] > 0.0:472 self.ATTM_SaturatedBarrens_WT_O[element] = self.ATTM_SaturatedBarrens_WT_O[element] - cohort_reduction473 if self.ATTM_SaturatedBarrens_WT_O[element] < 0.0:474 not_enough_land = not_enough_land + abs(self.ATTM_SaturatedBarrens_WT_O[element])475 not_enough_land_count = not_enough_land_count + 1476 self.ATTM_SaturatedBarrens_WT_O[element] = 0.0 477 if self.ATTM_Shrubs_WT_O[element] > 0.0:478 self.ATTM_Shrubs_WT_O[element] = self.ATTM_Shrubs_WT_O[element] - cohort_reduction479 if self.ATTM_Shrubs_WT_O[element] < 0.0:480 not_enough_land = not_enough_land + abs(self.ATTM_Shrubs_WT_O[element])481 not_enough_land_count = not_enough_land_count + 1482 self.ATTM_Shrubss_WT_O[element] = 0.0 483 # If not_enough_land_count is > 0, reduce size of lake484 if self.ATTM_LargeLakes_WT_Y[element] > 0. : lake_count = lake_count + 1.485 if self.ATTM_LargeLakes_WT_M[element] > 0. : lake_count = lake_count + 1.486 if self.ATTM_LargeLakes_WT_O[element] > 0. : lake_count = lake_count + 1.487 if self.ATTM_MediumLakes_WT_Y[element] > 0. : lake_count = lake_count + 1.488 if self.ATTM_MediumLakes_WT_M[element] > 0. : lake_count = lake_count + 1.489 if self.ATTM_MediumLakes_WT_O[element] > 0. : lake_count = lake_count + 1.490 if self.ATTM_SmallLakes_WT_Y[element] > 0. : lake_count = lake_count + 1.491 if self.ATTM_SmallLakes_WT_M[element] > 0. : lake_count = lake_count + 1.492 if self.ATTM_SmallLakes_WT_O[element] > 0. : lake_count = lake_count + 1.493 lake_reduction = not_enough_land / lake_count494 if self.ATTM_LargeLakes_WT_Y[element] > 0. :495 self.ATTM_LargeLakes_WT_Y[element] = self.ATTM_LargeLakes_WT_Y[element] - lake_reduction496 if self.ATTM_LargeLakes_WT_M[element] > 0. :497 self.ATTM_LargeLakes_WT_M[element] = self.ATTM_LargeLakes_WT_M[element] - lake_reduction498 if self.ATTM_LargeLakes_WT_O[element] > 0. :499 self.ATTM_LargeLakes_WT_O[element] = self.ATTM_LargeLakes_WT_O[element] - lake_reduction500 if self.ATTM_MediumLakes_WT_Y[element] > 0. :501 self.ATTM_MediumLakes_WT_Y[element] = self.ATTM_MediumLakes_WT_Y[element] - lake_reduction502 if self.ATTM_MediumLakes_WT_M[element] > 0. :503 self.ATTM_MediumLakes_WT_M[element] = self.ATTM_MediumLakes_WT_M[element] - lake_reduction504 if self.ATTM_MediumLakes_WT_O[element] > 0. :505 self.ATTM_MediumLakes_WT_O[element] = self.ATTM_MediumLakes_WT_O[element] - lake_reduction506 if self.ATTM_SmallLakes_WT_Y[element] > 0. :507 self.ATTM_SmallLakes_WT_Y[element] = self.ATTM_SmallLakes_WT_Y[element] - lake_reduction508 if self.ATTM_SmallLakes_WT_M [element] > 0. :509 self.ATTM_SmallLakes_WT_M[element] = self.ATTM_SmallLakes_WT_M[element] - lake_reduction510 if self.ATTM_SmallLakes_WT_O[element] > 0. :511 self.ATTM_SmallLakes_WT_O[element] = self.ATTM_SmallLakes_WT_O[element] - lake_reduction512 #-------------------------------------------------------------------------------513 # Check to ensure the fractional lake area does not exceed 1.0514 #515 # If Lake area is greater than or equal to 1., assume 1 large lake for the element that will516 # be divided up between the young, medium, and old age components (based upon517 # fractional relationship between young, medium and old age lakes).518 #519 # All other cohorts are also zeroed out (precaution/check).520 #--------------------------------------------------------------------------------521 ATTM_Lake_Area = self.ATTM_LargeLakes_WT_Y[element] + self.ATTM_LargeLakes_WT_M[element] + \522 self.ATTM_LargeLakes_WT_M[element] + self.ATTM_MediumLakes_WT_Y[element] + \523 self.ATTM_MediumLakes_WT_M[element] + self.ATTM_MediumLakes_WT_O[element] + \524 self.ATTM_SmallLakes_WT_Y[element] + self.ATTM_SmallLakes_WT_M[element] + \525 self.ATTM_SmallLakes_WT_O[element]526 if ATTM_Lake_Area >= 1.0:527 large_lake_total = self.ATTM_LargeLakes_WT_Y[element] + self.ATTM_LargeLakes_WT_M[element] + \528 self.ATTM_LargeLakes_WT_O[element]529 self.ATTM_LargeLakes_WT_Y[element] = self.ATTM_LargeLakes_WT_Y[element] / large_lake_total530 self.ATTM_LargeLakes_WT_M[element] = self.ATTM_LargeLakes_WT_M[element] / large_lake_total531 self.ATTM_LargeLakes_WT_O[element] = self.ATTM_LargeLakes_WT_O[element] / large_lake_total532 self.ATTM_MediumLakes_WT_Y[element] = 0.0533 self.ATTM_MediumLakes_WT_M[element] = 0.0534 self.ATTM_MediumLakes_WT_O[element] = 0.0535 self.ATTM_SmallLakes_WT_Y[element] = 0.0536 self.ATTM_SmallLakes_WT_M[element] = 0.0537 self.ATTM_SmallLakes_WT_O[element] = 0.0538 539 self.ATTM_CLC_WT_Y[element] = 0.0540 self.ATTM_CLC_WT_M[element] = 0.0541 self.ATTM_CLC_WT_O[element] = 0.0542 self.ATTM_CoastalWaters_WT_O[element] = 0.0543 self.ATTM_DrainedSlope_WT_Y[element] = 0.0544 self.ATTM_DrainedSlope_WT_M[element] = 0.0545 self.ATTM_DrainedSlope_WT_O[element] = 0.0546 self.ATTM_FCP_WT_Y[element] = 0.0547 self.ATTM_FCP_WT_M[element] = 0.0548 self.ATTM_FCP_WT_O[element] = 0.0549 self.ATTM_HCP_WT_Y[element] = 0.0550 self.ATTM_HCP_WT_M[element] = 0.0551 self.ATTM_HCP_WT_O[element] = 0.0552 self.ATTM_LCP_WT_Y[element] = 0.0553 self.ATTM_LCP_WT_M[element] = 0.0554 self.ATTM_LCP_WT_O[element] = 0.0555 self.ATTM_Meadow_WT_Y[element] = 0.0556 self.ATTM_Meadow_WT_M[element] = 0.0557 self.ATTM_Meadow_WT_O[element] = 0.0558 self.ATTM_NoData_WT_O[element] = 0.0559 self.ATTM_SandDunes_WT_Y[element] = 0.0560 self.ATTM_SandDunes_WT_M[element] = 0.0561 self.ATTM_SandDunes_WT_O[element] = 0.0562 self.SaturatedBarrens_WT_Y[element] = 0.0563 self.SaturatedBarrens_WT_M[element] = 0.0564 self.SaturatedBarrens_WT_O[element] = 0.0565 self.Shrubs_WT_O[element] = 0.0566 self.Urban_WT[element] = 0.0567 self.Rivers_WT_O[element] = 0.0568 self.Rivers_WT_M[element] = 0.0569 self.Rivers_WT_Y[element] = 0.0570 self.Ponds_WT_Y[element] = 0.0571 self.Ponds_WT_M[element] = 0.0572 self.Ponds_WT_O[element] = 0.0573 574# if 'Wet_NPG' in self.land_cohorts[element]:575# self.ATTM_Wet_NPG[element] = self.ATTM_Wet_NPG[element] - cohort_reduction576# if self.ATTM_Wet_NPG[element] < 0.0:577# not_enough_land = not_enough_land + abs(self.ATTM_Wet_NPG[element])578# self.ATTM_Wet_NPG[element] = 0.0579# self.land_cohorts[element].remove('Wet_NPG')580# if 'Wet_LCP' in self.land_cohorts[element]:581# self.ATTM_Wet_LCP[element] = self.ATTM_Wet_LCP[element] - cohort_reduction582# if self.ATTM_Wet_LCP[element] < 0.0:583# not_enough_land = not_enough_land + abs(self.ATTM_Wet_LCP[element])584# self.ATTM_Wet_LCP[element] = 0.0585# self.land_cohorts[element].remove('Wet_LCP')586# if 'Wet_CLC' in self.land_cohorts[element]:587# self.ATTM_Wet_CLC[element] = self.ATTM_Wet_CLC[element] - cohort_reduction588# if self.ATTM_Wet_CLC[element] < 0.0 :589# not_enough_land = not_enough_land + abs(self.ATTM_Wet_CLC[element])590# self.ATTM_Wet_CLC[element] = 0.0591# self.land_cohorts[element].remove('Wet_CLC')592# if 'Wet_FCP' in self.land_cohorts[element]:593# self.ATTM_Wet_FCP[element] = self.ATTM_Wet_FCP[element] - cohort_reduction594# if self.ATTM_Wet_FCP[element] < 0.0:595# not_enough_land = not_enough_land + abs(self.ATTM_Wet_FCP[element])596# self.ATTM_Wet_FCP[element] = 0.0597# self.land_cohorts[element].remove('Wet_FCP')598# if 'Wet_HCP' in self.land_cohorts[element]:599# self.ATTM_Wet_HCP[element] = self.ATTM_Wet_HCP[element] - cohort_reduction600# if self.ATTM_Wet_HCP[element] < 0.0:601# not_enough_land = not_enough_land + abs(self.ATTM_Wet_HCP[element])602# self.ATTM_Wet_HCP[element] = 0.0603# self.land_cohorts[element].remove('Wet_HCP')604# # --------------------------------------------------------605# # Increase lake fractional area by 'not enough land area'606# # --------------------------------------------------------607# self.ATTM_Lakes[element] = self.ATTM_Lakes[element] - not_enough_land608 609 ##########################################################################################610 # PONDS 611 ###########################################################################################612# if self.ATTM_Ponds[element] > 0.0 and self.ATTM_Ponds[element] < 1.0 :613 ATTM_Pond_Total = self.ATTM_Ponds_WT_Y[element] + self.ATTM_Ponds_WT_M[element] + \614 self.ATTM_Ponds_WT_O[element]615 if ATTM_Pond_Total > 0.0 and ATTM_Pond_Total < 1.0 :616 # --------------------------------------------------617 # Determine the fractional amount of pond expansion618 # --------------------------------------------------619 # If climate event happens, double the expansion constant620 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - -621 if self.climate_expansion_ponds[element] == 1.0:622 #pond_fraction_increase = self.ATTM_Ponds[element] * self.LakePond['Pond_Expansion'] *2.0623 pond_wt_fraction_increase_y = self.ATTM_Ponds_WT_Y[element] * self.LakePond['Pond_WT_Y_Expansion'] * 2.0624 pond_wt_fraction_increase_m = self.ATTM_Ponds_WT_M[element] * self.LakePond['Pond_WT_M_Expansion'] * 2.0625 pond_wt_fraction_increase_o = self.ATTM_Ponds_WT_O[element] * self.LakePond['Pond_WT_O_Expansion'] * 2.0626 self.climate_expansion_ponds[element] = 0.0627 else:628 #pond_fraction_increase = self.ATTM_Ponds[element] * self.LakePond['Pond_Expansion']629 pond_wt_fraction_increase_y = self.ATTM_Ponds_WT_Y[element] * self.LakePond['Pond_WT_Y_Expansion']630 pond_wt_fraction_increase_m = self.ATTM_Ponds_WT_M[element] * self.LakePond['Pond_WT_M_Expansion']631 pond_wt_fraction_increase_o = self.ATTM_Ponds_WT_O[element] * self.LakePond['Pond_WT_O_Expansion']632 633 pond_fraction_increase = pond_wt_fraction_increase_y + pond_wt_fraction_increase_m + \634 pond_wt_fraction_increase_o635 636 land_available = self.ATTM_CLC_WT_Y[element] + self.ATTM_CLC_WT_M[element] + \637 self.ATTM_CLC_WT_O[element] + self.ATTM_CoastalWaters_WT_O[element] + \638 self.ATTM_DrainedSlope_WT_Y[element] + self.ATTM_DrainedSlope_WT_M[element] + \639 self.ATTM_DrainedSlope_WT_O[element] + self.ATTM_FCP_WT_Y[element] + \640 self.ATTM_FCP_WT_M[element] + self.ATTM_FCP_WT_O[element] + \641 self.ATTM_HCP_WT_Y[element] + self.ATTM_HCP_WT_M[element] + \642 self.ATTM_HCP_WT_O[element] + self.ATTM_LCP_WT_Y[element] + \643 self.ATTM_LCP_WT_M[element] + self.ATTM_LCP_WT_O[element] + \644 self.ATTM_Meadow_WT_Y[element] + self.ATTM_Meadow_WT_M[element] + \645 self.ATTM_Meadow_WT_O[element] + self.ATTM_NoData_WT_O[element] + \646 self.ATTM_SandDunes_WT_Y[element] + self.ATTM_SandDunes_WT_M[element] + \647 self.ATTM_SandDunes_WT_O[element] + self.ATTM_SaturatedBarrens_WT_Y[element] + \648 self.ATTM_SaturatedBarrens_WT_M[element] + self.ATTM_SaturatedBarrens_WT_O[element] + \649 self.ATTM_Shrubs_WT_O[element]650 651 # ==================================================================================652 # Case 0:653 # The sum of the fractional pond area + pond_fraction_increase > the available654 # land available for pond expansion (not expanding into rivers, urban, lakes).655 #656 # In this case, the fractional pond area is equal to the total amount of land657 # cohorts and all the land cohorts are set to 0.0658 # ==================================================================================659 if pond_fraction_increase > land_available:660 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 661 #self.ATTM_Ponds[element] = self.ATTM_Ponds[element] + land_available662 self.ATTM_Ponds_WT_Y[element] = self.ATTM_Ponds_WT_Y[element] + \663 ((self.ATTM_Ponds_WT_Y[element] / ATTM_Pond_Total) * land_available)664 self.ATTM_Ponds_WT_M[element] = self.ATTM_Ponds_WT_M[element] + \665 ((self.ATTM_Ponds_WT_M[element] / ATTM_Pond_Total) * land_available)666 self.ATTM_Ponds_WT_O[element] = self.ATTM_Ponds_WT_O[element] + \667 ((self.ATTM_Ponds_WT_O[element] / ATTM_Pond_Total) * land_available)668 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -669# self.ATTM_Wet_NPG[element] = 0.0670# if 'Wet_NPG' in self.land_cohorts[element] :671# self.land_cohorts[element].remove('Wet_NPG')672# self.ATTM_Wet_LCP[element] = 0.0673# if 'Wet_LCP' in self.land_cohorts[element]:674# self.land_cohorts[element].remove('Wet_LCP')675# self.ATTM_Wet_CLC[element] = 0.0676# if 'Wet_CLC' in self.land_cohorts[element]:677# self.land_cohorts[element].remove('Wet_CLC')678# self.ATTM_Wet_FCP[element] = 0.0679# if 'Wet_FCP' in self.land_cohorts[element]:680# self.land_cohorts[element].remove('Wet_FCP')681# self.ATTM_Wet_HCP[element] = 0.0682# if 'Wet_HCP' in self.land_cohorts[element]:683# self.land_cohorts[element].remove('Wet_HCP')684# self.ATTM_Gra_NPG[element] = 0.0685 686# self.ATTM_Gra_LCP[element] = 0.0687# self.ATTM_Gra_FCP[element] = 0.0688# self.ATTM_Gra_HCP[element] = 0.0689# self.ATTM_Shr_NPG[element] = 0.0690# self.ATTM_Shr_LCP[element] = 0.0691# self.ATTM_Shr_FCP[element] = 0.0692# self.ATTM_Shr_HCP[element] = 0.0693 694 695 # elif len(self.land_cohorts[element]) == 0:696 # # all water and/or urban cohorts in the element697 # self.ATTM_Ponds[element] = self.ATTM_Ponds[element]698 699 else:700 # ==================================================================================701 # Case 1:702 # The sum of all the land cohorts equals or exceeds the fractional amount of lake703 # area increase. However, one or more of the land cohorts has a fractional area704 # less than (or equal to) the lake_proportional_reduction value. In this case,705 # the land cohort(s) with the fractional areas less than the lake_proportional_area706 # are reduced to zero and the excess expansion is carried by the remaining cohorts.707 #708 # This case may result in a cascading reduction of cohorts. For example, if on the709 # first pass one land cohort is zeroed out, the remaining fractional reduction added710 # to the remaining cohorts may result in a lake_proportional_area being greater than711 # one of the remaining land cohorts. In this case, the 2nd cohort will need to be712 # zeroed out and the remaining lake area expansion is passed on to the remaining713 # land cohorts.714 # -----------------------------------------------------------------------------------715 #self.ATTM_Ponds[element] = self.ATTM_Ponds[element] + pond_fraction_increase716 self.ATTM_Ponds_WT_Y[element] = self.ATTM_Ponds_WT_Y[element] + pond_wt_fraction_increase_y717 self.ATTM_Ponds_WT_M[element] = self.ATTM_Ponds_WT_M[element] + pond_wt_fraction_increase_m718 self.ATTM_Ponds_WT_O[element] = self.ATTM_Ponds_WT_O[element] + pond_wt_fraction_increase_o719 720 #cohort_reduction = pond_fraction_increase / len(self.land_cohorts[element])721 not_enough_land = 0.0722 not_enough_land_count = 0.0723 land_count = 0.0724 pond_count = 0.0725 # Determine land cohorts available for reduction in the element726 if self.ATTM_CLC_WT_Y[element] > 0.0: land_count = land_count + 1727 if self.ATTM_CLC_WT_M[element] > 0.0: land_count = land_count + 1728 if self.ATTM_CLC_WT_O[element] > 0.0: land_count = land_count + 1729 if self.ATTM_CoastalWaters_WT_O[element] > 0.0 : land_count = land_count + 1730 if self.ATTM_DrainedSlope_WT_Y[element] > 0.0 : land_count = land_count + 1731 if self.ATTM_DrainedSlope_WT_M[element] > 0.0 : land_count = land_count + 1732 if self.ATTM_DrainedSlope_WT_O[element] > 0.0 : land_count = land_count + 1733 if self.ATTM_FCP_WT_Y[element] > 0.0 : land_count = land_count + 1734 if self.ATTM_FCP_WT_M[element] > 0.0 : land_count = land_count + 1735 if self.ATTM_FCP_WT_O[element] > 0.0 : land_count = land_count + 1736 if self.ATTM_HCP_WT_Y[element] > 0.0 : land_count = land_count + 1737 if self.ATTM_HCP_WT_M[element] > 0.0 : land_count = land_count + 1738 if self.ATTM_HCP_WT_O[element] > 0.0 : land_count = land_count + 1739 if self.ATTM_LCP_WT_Y[element] > 0.0 : land_count = land_count + 1740 if self.ATTM_LCP_WT_M[element] > 0.0 : land_count = land_count + 1741 if self.ATTM_LCP_WT_O[element] > 0.0 : land_count = land_count + 1742 if self.ATTM_Meadow_WT_Y[element] > 0.0 : land_count = land_count + 1743 if self.ATTM_Meadow_WT_M[element] > 0.0 : land_count = land_count + 1744 if self.ATTM_Meadow_WT_O[element] > 0.0 : land_count = land_count + 1745 if self.ATTM_NoData_WT_O[element] > 0.0 : land_count = land_count + 1746 if self.ATTM_SandDunes_WT_Y[element] > 0.0 : land_count = land_count + 1747 if self.ATTM_SandDunes_WT_M[element] > 0.0 : land_count = land_count + 1748 if self.ATTM_SandDunes_WT_O[element] > 0.0 : land_count = land_count + 1749 if self.ATTM_SaturatedBarrens_WT_Y[element] > 0.0 : land_count = land_count + 1750 if self.ATTM_SaturatedBarrens_WT_M[element] > 0.0 : land_count = land_count + 1751 if self.ATTM_SaturatedBarrens_WT_O[element] > 0.0 : land_count = land_count + 1752 if self.ATTM_Shrubs_WT_O[element] > 0.0 : land_count = land_count + 1753 # Determine proportional reduction for land cohorts present754 cohort_reduction = pond_fraction_increase / land_count755 # Sequence through land cohorts and reduce as appropriate756 if self.ATTM_CLC_WT_Y[element] > 0.0:757 self.ATTM_CLC_WT_Y[element] = self.ATTM_CLC_WT_Y[element] - cohort_reduction758 if self.ATTM_CLC_WT_Y[element] < 0.0:759 not_enough_land = not_enough_land + abs(self.ATTM_CLC_WT_Y[element])760 not_enough_land_count = not_enough_land_count + 1761 self.ATTM_CLC_WT_Y[element] = 0.0762 if self.ATTM_CLC_WT_M[element] > 0.0:763 self.ATTM_CLC_WT_M[element] = self.ATTM_CLC_WT_M[element] - cohort_reduction764 if self.ATTM_CLC_WT_M[element] < 0.0:765 not_enough_land = not_enough_land + abs(self.ATTM_CLC_WT_M[element])766 not_enough_land_count = not_enough_land_count + 1767 self.ATTM_CLC_WT_M[element] = 0.0768 if self.ATTM_CLC_WT_O[element] > 0.0:769 self.ATTM_CLC_WT_O[element] = self.ATTM_CLC_WT_O[element] - cohort_reduction770 if self.ATTM_CLC_WT_O[element] < 0.0:771 not_enough_land = not_enough_land + abs(self.ATTM_CLC_WT_O[element])772 not_enough_land_count = not_enough_land_count + 1773 self.ATTM_CLC_WT_O[element] = 0.0774 if self.ATTM_CoastalWaters_WT_O[element] > 0.0:775 self.ATTM_CoastalWaters_WT_O[element] = self.ATTM_CoastalWaters_WT_O[element] - cohort_reduction776 if self.ATTM_CoastalWaters_WT_O[element] < 0.0:777 not_enough_land = not_enough_land + abs(self.ATTM_CoastalWaters_WT_O[element])778 not_enough_land_count = not_enough_land_count + 1779 self.ATTM_CoastalWaters_WT_O[element] = 0.0 780 if self.ATTM_DrainedSlope_WT_Y[element] > 0.0:781 self.ATTM_DrainedSlope_WT_Y[element] = self.ATTM_DrainedSlope_WT_Y[element] - cohort_reduction782 if self.ATTM_DrainedSlope_WT_Y[element] < 0.0:783 not_enough_land = not_enough_land + abs(self.ATTM_DrainedSlope_WT_Y[element])784 not_enough_land_count = not_enough_land_count + 1785 self.ATTM_DrainedSlope_WT_Y[element] = 0.0786 if self.ATTM_DrainedSlope_WT_M[element] > 0.0:787 self.ATTM_DrainedSlope_WT_M[element] = self.ATTM_DrainedSlope_WT_M[element] - cohort_reduction788 if self.ATTM_DrainedSlope_WT_M[element] < 0.0:789 not_enough_land = not_enough_land + abs(self.ATTM_DrainedSlope_WT_M[element])790 not_enough_land_count = not_enough_land_count + 1791 self.ATTM_DrainedSlope_WT_M[element] = 0.0792 if self.ATTM_DrainedSlope_WT_O[element] > 0.0:793 self.ATTM_DrainedSlope_WT_O[element] = self.ATTM_DrainedSlope_WT_O[element] - cohort_reduction794 if self.ATTM_DrainedSlope_WT_O[element] < 0.0:795 not_enough_land = not_enough_land + abs(self.ATTM_DrainedSlope_WT_O[element])796 not_enough_land_count = not_enough_land_count + 1797 self.ATTM_DrainedSlope_WT_O[element] = 0.0798 if self.ATTM_FCP_WT_Y[element] > 0.0:799 self.ATTM_FCP_WT_Y[element] = self.ATTM_FCP_WT_Y[element] - cohort_reduction800 if self.ATTM_FCP_WT_Y[element] < 0.0:801 not_enough_land = not_enough_land + abs(self.ATTM_FCP_WT_Y[element])802 not_enough_land_count = not_enough_land_count + 1803 self.ATTM_FCP_WT_Y[element] = 0.0804 if self.ATTM_FCP_WT_M[element] > 0.0:805 self.ATTM_FCP_WT_M[element] = self.ATTM_FCP_WT_M[element] - cohort_reduction806 if self.ATTM_FCP_WT_M[element] < 0.0:807 not_enough_land = not_enough_land + abs(self.ATTM_FCP_WT_M[element])808 not_enough_land_count = not_enough_land_count + 1809 self.ATTM_FCP_WT_M[element] = 0.0810 if self.ATTM_FCP_WT_O[element] > 0.0:811 self.ATTM_FCP_WT_O[element] = self.ATTM_FCP_WT_O[element] - cohort_reduction812 if self.ATTM_FCP_WT_O[element] < 0.0:813 not_enough_land = not_enough_land + abs(self.ATTM_FCP_WT_O[element])814 not_enough_land_count = not_enough_land_count + 1815 self.ATTM_FCP_WT_O[element] = 0.0816 if self.ATTM_HCP_WT_Y[element] > 0.0:817 self.ATTM_HCP_WT_Y[element] = self.ATTM_HCP_WT_Y[element] - cohort_reduction818 if self.ATTM_HCP_WT_Y[element] < 0.0:819 not_enough_land = not_enough_land + abs(self.ATTM_HCP_WT_Y[element])820 not_enough_land_count = not_enough_land_count + 1821 self.ATTM_HCP_WT_Y[element] = 0.0822 if self.ATTM_HCP_WT_M[element] > 0.0:823 self.ATTM_HCP_WT_M[element] = self.ATTM_HCP_WT_M[element] - cohort_reduction824 if self.ATTM_HCP_WT_M[element] < 0.0:825 not_enough_land = not_enough_land + abs(self.ATTM_HCP_WT_M[element])826 not_enough_land_count = not_enough_land_count + 1827 self.ATTM_HCP_WT_M[element] = 0.0828 if self.ATTM_HCP_WT_O[element] > 0.0:829 self.ATTM_HCP_WT_O[element] = self.ATTM_HCP_WT_O[element] - cohort_reduction830 if self.ATTM_HCP_WT_O[element] < 0.0:831 not_enough_land = not_enough_land + abs(self.ATTM_HCP_WT_O[element])832 not_enough_land_count = not_enough_land_count + 1833 self.ATTM_HCP_WT_O[element] = 0.0834 if self.ATTM_LCP_WT_Y[element] > 0.0:835 self.ATTM_LCP_WT_Y[element] = self.ATTM_LCP_WT_Y[element] - cohort_reduction836 if self.ATTM_LCP_WT_Y[element] < 0.0:837 not_enough_land = not_enough_land + abs(self.ATTM_LCP_WT_Y[element])838 not_enough_land_count = not_enough_land_count + 1839 self.ATTM_LCP_WT_Y[element] = 0.0840 if self.ATTM_LCP_WT_M[element] > 0.0:841 self.ATTM_LCP_WT_M[element] = self.ATTM_LCP_WT_M[element] - cohort_reduction842 if self.ATTM_LCP_WT_M[element] < 0.0:843 not_enough_land = not_enough_land + abs(self.ATTM_LCP_WT_M[element])844 not_enough_land_count = not_enough_land_count + 1845 self.ATTM_LCP_WT_M[element] = 0.0846 if self.ATTM_LCP_WT_O[element] > 0.0:847 self.ATTM_LCP_WT_O[element] = self.ATTM_LCP_WT_O[element] - cohort_reduction848 if self.ATTM_LCP_WT_O[element] < 0.0:849 not_enough_land = not_enough_land + abs(self.ATTM_LCP_WT_O[element])850 not_enough_land_count = not_enough_land_count + 1851 self.ATTM_LCP_WT_O[element] = 0.0852 if self.ATTM_Meadow_WT_Y[element] > 0.0:853 self.ATTM_Meadow_WT_Y[element] = self.ATTM_Meadow_WT_Y[element] - cohort_reduction854 if self.ATTM_Meadow_WT_Y[element] < 0.0:855 not_enough_land = not_enough_land + abs(self.ATTM_Meadow_WT_Y[element])856 not_enough_land_count = not_enough_land_count + 1857 self.ATTM_Meadow_WT_Y[element] = 0.0858 if self.ATTM_Meadow_WT_M[element] > 0.0:859 self.ATTM_Meadow_WT_M[element] = self.ATTM_Meadow_WT_M[element] - cohort_reduction860 if self.ATTM_Meadow_WT_M[element] < 0.0:861 not_enough_land = not_enough_land + abs(self.ATTM_Meadow_WT_M[element])862 not_enough_land_count = not_enough_land_count + 1863 self.ATTM_Meadow_WT_M[element] = 0.0864 if self.ATTM_Meadow_WT_O[element] > 0.0:865 self.ATTM_Meadow_WT_O[element] = self.ATTM_Meadow_WT_O[element] - cohort_reduction866 if self.ATTM_Meadow_WT_O[element] < 0.0:867 not_enough_land = not_enough_land + abs(self.ATTM_Meadow_WT_O[element])868 not_enough_land_count = not_enough_land_count + 1869 self.ATTM_Meadow_WT_O[element] = 0.0870 if self.ATTM_SandDunes_WT_Y[element] > 0.0:871 self.ATTM_SandDunes_WT_Y[element] = self.ATTM_SandDunes_WT_Y[element] - cohort_reduction872 if self.ATTM_SandDunes_WT_Y[element] < 0.0:873 not_enough_land = not_enough_land + abs(self.ATTM_SandDunes_WT_Y[element])874 not_enough_land_count = not_enough_land_count + 1875 self.ATTM_SandDunes_WT_Y[element] = 0.0876 if self.ATTM_SandDunes_WT_M[element] > 0.0:877 self.ATTM_SandDunes_WT_M[element] = self.ATTM_SandDunes_WT_M[element] - cohort_reduction878 if self.ATTM_SandDunes_WT_M[element] < 0.0:879 not_enough_land = not_enough_land + abs(self.ATTM_SandDunes_WT_M[element])880 not_enough_land_count = not_enough_land_count + 1881 self.ATTM_SandDunes_WT_M[element] = 0.0882 if self.ATTM_SandDunes_WT_O[element] > 0.0:883 self.ATTM_SandDunes_WT_O[element] = self.ATTM_SandDunes_WT_O[element] - cohort_reduction884 if self.ATTM_SandDunes_WT_O[element] < 0.0:885 not_enough_land = not_enough_land + abs(self.ATTM_SandDunes_WT_O[element])886 not_enough_land_count = not_enough_land_count + 1887 self.ATTM_SandDunes_WT_O[element] = 0.0888 if self.ATTM_NoData_WT_O[element] > 0.0:889 self.ATTM_NoData_WT_O[element] = self.ATTM_NoData_WT_O[element] - cohort_reduction890 if self.ATTM_NoData_WT_O[element] < 0.0:891 not_enough_land = not_enough_land + abs(self.ATTM_NoData_WT_O[element])892 not_enough_land_count = not_enough_land_count + 1893 self.ATTM_NoData_WT_O[element] = 0.0894 if self.ATTM_SaturatedBarrens_WT_Y[element] > 0.0:895 self.ATTM_SaturatedBarrens_WT_Y[element] = self.ATTM_SaturatedBarrens_WT_Y[element] - cohort_reduction896 if self.ATTM_SaturatedBarrens_WT_Y[element] < 0.0:897 not_enough_land = not_enough_land + abs(self.ATTM_SaturatedBarrens_WT_Y[element])898 not_enough_land_count = not_enough_land_count + 1899 self.ATTM_SaturatedBarrens_WT_Y[element] = 0.0900 if self.ATTM_SaturatedBarrens_WT_M[element] > 0.0:901 self.ATTM_SaturatedBarrens_WT_M[element] = self.ATTM_SaturatedBarrens_WT_M[element] - cohort_reduction902 if self.ATTM_SaturatedBarrens_WT_M[element] < 0.0:903 not_enough_land = not_enough_land + abs(self.ATTM_SaturatedBarrens_WT_M[element])904 not_enough_land_count = not_enough_land_count + 1905 self.ATTM_SaturatedBarrens_WT_M[element] = 0.0906 if self.ATTM_SaturatedBarrens_WT_O[element] > 0.0:907 self.ATTM_SaturatedBarrens_WT_O[element] = self.ATTM_SaturatedBarrens_WT_O[element] - cohort_reduction908 if self.ATTM_SaturatedBarrens_WT_O[element] < 0.0:909 not_enough_land = not_enough_land + abs(self.ATTM_SaturatedBarrens_WT_O[element])910 not_enough_land_count = not_enough_land_count + 1911 self.ATTM_SaturatedBarrens_WT_O[element] = 0.0 912 if self.ATTM_Shrubs_WT_O[element] > 0.0:913 self.ATTM_Shrubs_WT_O[element] = self.ATTM_Shrubs_WT_O[element] - cohort_reduction914 if self.ATTM_Shrubs_WT_O[element] < 0.0:915 not_enough_land = not_enough_land + abs(self.ATTM_Shrubs_WT_O[element])916 not_enough_land_count = not_enough_land_count + 1917 self.ATTM_Shrubss_WT_O[element] = 0.0 918 # If not_enough_land_count is > 0, reduce size of ponds919 if self.ATTM_Ponds_WT_Y[element] > 0.0 : pond_count = pond_count + 1.920 if self.ATTM_Ponds_WT_M[element] > 0.0 : pond_count = pond_count + 1.921 if self.ATTM_Ponds_WT_O[element] > 0.0 : pond_count = pond_count + 1.922 pond_reduction = not_enough_land / pond_count923 if self.ATTM_Ponds_WT_Y[element] > 0. :924 self.ATTM_Ponds_WT_Y[element] = self.ATTM_Ponds_WT_Y[element] - pond_reduction925 if self.ATTM_Ponds_WT_M[element] > 0. :926 self.ATTM_Ponds_WT_M[element] = self.ATTM_Ponds_WT_M[element] - pond_reduction927 if self.ATTM_Ponds_WT_O[element] > 0. :928 self.ATTM_Ponds_WT_O[element] = self.ATTM_Ponds_WT_O[element] - pond_reduction929 #-------------------------------------------------------------------------------930 # Check to ensure the fractional pond area does not exceed 1.0931 #932 # If Pond area is greater than or equal to 1., assume 1 for all ponds for the element that will933 # be divided up between the young, medium, and old age components (based upon934 # fractional relationship between young, medium and old age lakes).935 #936 # All other cohorts are also zeroed out (precaution/check).937 #--------------------------------------------------------------------------------938 ATTM_Pond_Area = self.ATTM_Ponds_WT_Y[element] + self.ATTM_Ponds_WT_M[element] + \939 self.ATTM_Ponds_WT_O[element]940 if ATTM_Pond_Area >= 1.0:941 self.ATTM_Ponds_WT_Y[element] = self.ATTM_Ponds_WT_Y[element] / ATTM_Pond_Area942 self.ATTM_Ponds_WT_M[element] = self.ATTM_Ponds_WT_M[element] / ATTM_Pond_Area943 self.ATTM_Ponds_WT_O[element] = self.ATTM_Ponds_WT_O[element] / ATTM_Pond_Area944 self.ATTM_LargeLakes_WT_Y[element] = 0.0945 self.ATTM_LargeLakes_WT_M[element] = 0.0946 self.ATTM_LargeLakes_WT_O[element] = 0.0947 self.ATTM_MediumLakes_WT_Y[element] = 0.0948 self.ATTM_MediumLakes_WT_M[element] = 0.0949 self.ATTM_MediumLakes_WT_O[element] = 0.0950 self.ATTM_SmallLakes_WT_Y[element] = 0.0951 self.ATTM_SmallLakes_WT_M[element] = 0.0952 self.ATTM_SmallLakes_WT_O[element] = 0.0953 self.ATTM_CLC_WT_Y[element] = 0.0954 self.ATTM_CLC_WT_M[element] = 0.0955 self.ATTM_CLC_WT_O[element] = 0.0956 self.ATTM_CoastalWaters_WT_O[element] = 0.0957 self.DrainedSlope_WT_Y[element] = 0.0958 self.DrainedSlope_WT_M[element] = 0.0959 self.DrainedSlope_WT_O[element] = 0.0960 self.FCP_WT_Y[element] = 0.0961 self.FCP_WT_M[element] = 0.0962 self.FCP_WT_O[element] = 0.0963 self.HCP_WT_Y[element] = 0.0964 self.HCP_WT_M[element] = 0.0965 self.HCP_WT_O[element] = 0.0966 self.LCP_WT_Y[element] = 0.0967 self.LCP_WT_M[element] = 0.0968 self.LCP_WT_O[element] = 0.0969 self.Meadow_WT_Y[element] = 0.0970 self.Meadow_WT_M[element] = 0.0971 self.Meadow_WT_O[element] = 0.0972 self.NoData_WT_O[element] = 0.0973 self.SandDunes_WT_Y[element] = 0.0974 self.SandDunes_WT_M[element] = 0.0975 self.SandDunes_WT_O[element] = 0.0976 self.SaturatedBarrens_WT_Y[element] = 0.0977 self.SaturatedBarrens_WT_M[element] = 0.0978 self.SaturatedBarrens_WT_O[element] = 0.0979 self.Shrubs_WT_O[element] = 0.0980 self.Urban_WT[element] = 0.0981 self.Rivers_WT_Y[element] = 0.0982 self.Rivers_WT_M[element] = 0.0983 self.Rivers_WT_O[element] = 0.0984# # -------------------------------------985# # Reduce all appropriate land cohorts986# # -------------------------------------987# if 'Wet_NPG' in self.land_cohorts[element]:988# self.ATTM_Wet_NPG[element] = self.ATTM_Wet_NPG[element] - cohort_reduction989# if self.ATTM_Wet_NPG[element] < 0.0:990# not_enough_land = not_enough_land + abs(self.ATTM_Wet_NPG[element])991# self.ATTM_Wet_NPG[element] = 0.0992# self.land_cohorts[element].remove('Wet_NPG')993# if 'Wet_LCP' in self.land_cohorts[element]:994# self.ATTM_Wet_LCP[element] = self.ATTM_Wet_LCP[element] - cohort_reduction995# if self.ATTM_Wet_LCP[element] < 0.0:996# not_enough_land = not_enough_land + abs(self.ATTM_Wet_LCP[element])997# self.ATTM_Wet_LCP[element] = 0.0998# self.land_cohorts[element].remove('Wet_LCP')999# if 'Wet_CLC' in self.land_cohorts[element]:1000# self.ATTM_Wet_CLC[element] = self.ATTM_Wet_CLC[element] - cohort_reduction1001# if self.ATTM_Wet_CLC[element] < 0.0 :1002# not_enough_land = not_enough_land + abs(self.ATTM_Wet_CLC[element])1003# self.ATTM_Wet_CLC[element] = 0.01004# self.land_cohorts[element].remove('Wet_CLC')1005# if 'Wet_FCP' in self.land_cohorts[element]:1006# self.ATTM_Wet_FCP[element] = self.ATTM_Wet_FCP[element] - cohort_reduction1007# if self.ATTM_Wet_FCP[element] < 0.0:1008# not_enough_land = not_enough_land + abs(self.ATTM_Wet_FCP[element])1009# self.ATTM_Wet_FCP[element] = 0.01010# self.land_cohorts[element].remove('Wet_FCP')1011# if 'Wet_HCP' in self.land_cohorts[element]:1012# self.ATTM_Wet_HCP[element] = self.ATTM_Wet_HCP[element] - cohort_reduction1013# if self.ATTM_Wet_HCP[element] < 0.0:1014# not_enough_land = not_enough_land + abs(self.ATTM_Wet_HCP[element])1015# self.ATTM_Wet_HCP[element] = 0.01016# self.land_cohorts[element].remove('Wet_HCP')1017# # ------------------------------1018# # Increase pond fractional area1019# # ------------------------------1020# self.ATTM_Ponds[element] = self.ATTM_Ponds[element] - not_enough_land1021 1022#===============================================================================================1023def pond_infill(self, element, time):1024 """1025 The purpose of this module is to infill ponds at a prescribed rate with vegetation,1026 which will presumably be non-polygonal ground.1027 # - - -- - - - - - - -- - - - - - - - -- - - - - - - - -- - - - -- - - -1028 !!! I should double check to see if non-polygonal ground is the correct1029 !!! transition ...1030 # - - - - - - - - - - - - - - - - - --- - - - - - - - - - - - - - - - - -1031 This module is developed due to paper that states with warming temperatures,1032 ponds are shrinking due in part to infilling of vegetation. Paper is in press1033 and was set out by Anna L. in March 2015.1034 # - - - - - -------------------------------------------------------------------1035 I think initially, I will set pond infilling to occur every time step. I might1036 try to infill when temperature in year N is greater than temperature in year N-1.1037 #-------------------------------------------------------------------------------1038 """1039# if self.ATTM_Ponds[element] > 0.0 and self.ATTM_Ponds[element] < 1.0:1040 pond_area = self.ATTM_Ponds_WT_Y[element] + self.ATTM_Ponds_WT_M[element] + self.ATTM_Ponds_WT_O[element]1041 if pond_area > 0.0 and pond_area < 1.0 :1042 # Is this the first time step? If yes, no infilling occurs1043 if time == 0:1044 pass1045 else:1046 # If Degree Days are greater than previous time step, infill1047 if self.TDD[time, element] > self.TDD[time-1, element]:1048 #infill = self.ATTM_Ponds[element] * self.LakePond['Pond_Infill_Constant']1049 infill_y = self.ATTM_Ponds_WT_Y[element] * self.LakePond['Pond_WT_Y_Infill_Constant']1050 infill_m = self.ATTM_Ponds_WT_M[element] * self.LakePond['Pond_WT_M_Infill_Constant']1051 infill_o = self.ATTM_Ponds_WT_O[element] * self.LakePond['Pond_WT_O_Infill_Constant']1052 # Reduce Pond size and increase WetNPG size1053 #self.ATTM_Ponds[element] = self.ATTM_Ponds[element] - infill1054 #self.ATTM_Wet_NPG[element] = self.ATTM_Wet_NPG[element] + infill1055 self.ATTM_Ponds_WT_Y[element] = self.ATTM_Ponds_WT_Y[element] - infill_y1056 self.ATTM_Ponds_WT_M[element] = self.ATTM_Ponds_WT_M[element] - infill_m1057 self.ATTM_Ponds_WT_O[element] = self.ATTM_Ponds_WT_O[element] - infill_o1058 self.ATTM_Meadow_WT_Y[element] = self.ATTM_Meadow_WT_Y[element] + infill_y1059 self.ATTM_Meadow_WT_M[element] = self.ATTM_Meadow_WT_M[element] + infill_m...

Full Screen

Full Screen

cohort_check.py

Source:cohort_check.py Github

copy

Full Screen

1import numpy as np2import gdal, os, sys, glob, random3import pylab as pl4from decimal import *5getcontext().prec = 46def cohort_start(self, element, time):7 """8 The purpose of this module is to define the total fractional areas9 of all the cohorts in each model element.10 """11 # fraction_start = self.ATTM_Wet_NPG[element] + self.ATTM_Wet_LCP[element] + \12 # self.ATTM_Wet_CLC[element] + self.ATTM_Wet_FCP[element] + \13 # self.ATTM_Wet_HCP[element] + self.ATTM_Gra_NPG[element] + \14 # self.ATTM_Gra_LCP[element] + self.ATTM_Gra_FCP[element] + \15 # self.ATTM_Gra_HCP[element] + self.ATTM_Shr_NPG[element] + \16 # self.ATTM_Shr_LCP[element] + self.ATTM_Shr_FCP[element] + \17 # self.ATTM_Shr_HCP[element] + self.ATTM_Urban[element] + \18 # self.ATTM_Rivers[element] + self.ATTM_Ponds[element] + \19 # self.ATTM_Lakes[element]20 fraction_start = self.ATTM_CLC_WT_Y[element] + self.ATTM_CLC_WT_M[element] + \21 self.ATTM_CLC_WT_O[element] + self.ATTM_CoastalWaters_WT_O[element] + \22 self.ATTM_DrainedSlope_WT_Y[element] + self.ATTM_DrainedSlope_WT_M[element] + \23 self.ATTM_DrainedSlope_WT_O[element] + self.ATTM_FCP_WT_Y[element] + \24 self.ATTM_FCP_WT_M[element] + self.ATTM_FCP_WT_O[element] + \25 self.ATTM_HCP_WT_Y[element] + self.ATTM_HCP_WT_M[element] + \26 self.ATTM_HCP_WT_O[element] + self.ATTM_LCP_WT_Y[element] + \27 self.ATTM_LCP_WT_M[element] + self.ATTM_LCP_WT_O[element] + \28 self.ATTM_Meadow_WT_Y[element] + self.ATTM_Meadow_WT_M[element] + \29 self.ATTM_Meadow_WT_O[element] + self.ATTM_NoData_WT_O[element] + \30 self.ATTM_SandDunes_WT_Y[element] + self.ATTM_SandDunes_WT_M[element] + \31 self.ATTM_SandDunes_WT_O[element] + self.ATTM_SaturatedBarrens_WT_Y[element] + \32 self.ATTM_SaturatedBarrens_WT_M[element] + self.ATTM_SaturatedBarrens_WT_O[element] + \33 self.ATTM_Shrubs_WT_O[element] + self.ATTM_Urban_WT[element] + \34 self.ATTM_LargeLakes_WT_Y[element] + self.ATTM_LargeLakes_WT_M[element] + \35 self.ATTM_LargeLakes_WT_O[element] + self.ATTM_MediumLakes_WT_Y[element] + \36 self.ATTM_MediumLakes_WT_M[element] + self.ATTM_MediumLakes_WT_O[element] + \37 self.ATTM_SmallLakes_WT_Y[element] + self.ATTM_SmallLakes_WT_M[element] + \38 self.ATTM_SmallLakes_WT_O[element] + self.ATTM_Ponds_WT_Y[element] + \39 self.ATTM_Ponds_WT_M[element] + self.ATTM_Ponds_WT_O[element] + \40 self.ATTM_Rivers_WT_Y[element] + self.ATTM_Rivers_WT_M[element] + \41 self.ATTM_Rivers_WT_O[element]42 43 ## if element == 700:44 ## print 'element : ', element45 ## print 'Wetland Meadow Start: ', self.ATTM_Wet_NPG[element]46 ## print 'Wetland LCP Start: ', self.ATTM_Wet_LCP[element]47 ## print 'Wetland CLC Start: ', self.ATTM_Wet_CLC[element]48 ## print 'Wetland FCP Start: ', self.ATTM_Wet_CLC[element]49 ## print 'Wetland HCP Start: ', self.ATTM_Wet_HCP[element]50 ## print 'Lakes Start: ', self.ATTM_Lakes[element]51 ## print 'Ponds Start: ', self.ATTM_Ponds[element]52 ## print 'Urban Start: ', self.ATTM_Urban[element]53 ## print 'Rivers Start: ', self. ATTM_Rivers[element]54 ## print 'Total: ', fraction_start55 ## print ' '56 return fraction_start57def cohort_check(self, element, time, cohort_start):58 """59 The purpose of this module is to run a 'mass-balance' of the60 fractional areas of all the cohorts. After each time step,61 the total fractional area of all the cohorts should equal62 the prior time-step fractional area of cohorts.63 In most elements the total sum of all the fractional cohorts64 should be equal to 1.0. There are a few cases, such elements65 along the edge of the model domain and along the rivers,66 that have a total fractional area that is less than 1.0.67 """68 # fraction_end = np.round(self.ATTM_Wet_NPG[element] + self.ATTM_Wet_LCP[element] + \69 # self.ATTM_Wet_CLC[element] + self.ATTM_Wet_FCP[element] + \70 # self.ATTM_Wet_HCP[element] + self.ATTM_Gra_NPG[element] + \71 # self.ATTM_Gra_LCP[element] + self.ATTM_Gra_FCP[element] + \72 # self.ATTM_Gra_HCP[element] + self.ATTM_Shr_NPG[element] + \73 # self.ATTM_Shr_LCP[element] + self.ATTM_Shr_FCP[element] + \74 # self.ATTM_Shr_HCP[element] + self.ATTM_Urban[element] + \75 # self.ATTM_Rivers[element] + self.ATTM_Ponds[element] + \76 # self.ATTM_Lakes[element], decimals = 4)77 fraction_end = np.round(self.ATTM_CLC_WT_Y[element] + self.ATTM_CLC_WT_M[element] + \78 self.ATTM_CLC_WT_O[element] + self.ATTM_CoastalWaters_WT_O[element] + \79 self.ATTM_DrainedSlope_WT_Y[element] + self.ATTM_DrainedSlope_WT_M[element] + \80 self.ATTM_DrainedSlope_WT_O[element] + self.ATTM_FCP_WT_Y[element] + \81 self.ATTM_FCP_WT_M[element] + self.ATTM_FCP_WT_O[element] + \82 self.ATTM_HCP_WT_Y[element] + self.ATTM_HCP_WT_M[element] + \83 self.ATTM_HCP_WT_O[element] + self.ATTM_LCP_WT_Y[element] + \84 self.ATTM_LCP_WT_M[element] + self.ATTM_LCP_WT_O[element] + \85 self.ATTM_Meadow_WT_Y[element] + self.ATTM_Meadow_WT_M[element] + \86 self.ATTM_Meadow_WT_O[element] + self.ATTM_NoData_WT_O[element] + \87 self.ATTM_SandDunes_WT_Y[element] + self.ATTM_SandDunes_WT_M[element] + \88 self.ATTM_SandDunes_WT_O[element] + self.ATTM_SaturatedBarrens_WT_Y[element] + \89 self.ATTM_SaturatedBarrens_WT_M[element] + self.ATTM_SaturatedBarrens_WT_O[element] + \90 self.ATTM_Shrubs_WT_O[element] + self.ATTM_Urban_WT[element] + \91 self.ATTM_LargeLakes_WT_Y[element] + self.ATTM_LargeLakes_WT_M[element] + \92 self.ATTM_LargeLakes_WT_O[element] + self.ATTM_MediumLakes_WT_Y[element] + \93 self.ATTM_MediumLakes_WT_M[element] + self.ATTM_MediumLakes_WT_O[element] + \94 self.ATTM_SmallLakes_WT_Y[element] + self.ATTM_SmallLakes_WT_M[element] + \95 self.ATTM_SmallLakes_WT_O[element] + self.ATTM_Ponds_WT_Y[element] + \96 self.ATTM_Ponds_WT_M[element] + self.ATTM_Ponds_WT_O[element] + \97 self.ATTM_Rivers_WT_Y[element] + self.ATTM_Rivers_WT_M[element] + \98 self.ATTM_Rivers_WT_O[element], decimals = 4)99 100 101 if abs(cohort_start - fraction_end) > 0.1:102 print 'There is a mass balance problem in element: '+str(element)+' at time: ', time103 print 'start: ', cohort_start104 print 'end: ', fraction_end105 print ' '106 print 'Final land cohort fractions: '107 print ' Wetland Tundra Meadows:'108 print ' Young: ', self.ATTM_Meadow_WT_Y[element]109 print ' Medium: ', self.ATTM_Meadow_WT_M[element]110 print ' Old: ', self.ATTM_Meadow_WT_O[element]111 print ' Wetland Tundra Low Center Polygons:'112 print ' Young: ', self.ATTM_LCP_WT_Y[element]113 print ' Medium: ', self.ATTM_LCP_WT_M[element]114 print ' Old: ', self.ATTM_LCP_WT_O[element]115 print ' Wetland Tundra Coalescent Low Center Polygons:'116 print ' Young: ', self.ATTM_CLC_WT_Y[element]117 print ' Medium: ', self.ATTM_CLC_WT_M[element]118 print ' Old: ', self.ATTM_CLC_WT_O[element]119 print ' Wetland Tundra Flat Center Polygons:'120 print ' Young: ', self.ATTM_FCP_WT_Y[element]121 print ' Medium: ', self.ATTM_FCP_WT_M[element]122 print ' Old: ', self.ATTM_FCP_WT_O[element]123 print ' Wetland Tundra High Center Polygons: '124 print ' Young: ', self.ATTM_HCP_WT_Y[element]125 print ' Medium: ', self.ATTM_HCP_WT_M[element]126 print ' Old: ', self.ATTM_HCP_WT_O[element]127 print ' Wetland Tundra Large Lakes: '128 print ' Young: ', self.ATTM_LargeLakes_WT_Y[element]129 print ' Medium: ', self.ATTM_LargeLakes_WT_M[element]130 print ' Old: ', self.ATTM_LargeLakes_WT_O[element]131 print ' Wetland Tundra Medium Lakes: '132 print ' Young: ', self.ATTM_MediumLakes_WT_Y[element]133 print ' Medium: ', self.ATTM_MediumLakes_WT_M[element]134 print ' Old; ', self.ATTM_MediumLakes_WT_O[element]135 print ' Wetland Tundra Small Lakes: '136 print ' Young: ', self.ATTM_SmallLakes_WT_Y[element]137 print ' Medium: ', self.ATTM_SmallLakes_WT_M[element]138 print ' Old: ', self.ATTM_SmallLakes_WT_O[element]139 print ' Wetland Tundra Ponds: '140 print ' Young: ', self.ATTM_Ponds_WT_Y[element]141 print ', Medium: ', self.ATTM_Ponds_WT_M[element]142 print ', Old: ', self.ATTM_Ponds_WT_O[element]143 print ', Wetland Tundra Rivers: '144 print ', Young: ', self.ATTM_Rivers_WT_Y[element]145 print ', Medium: ', self.ATTM_Rivers_WT_M[element]146 print ', Old: ', self.ATTM_Rivers_WT_O[element]147 print ', Wetland Tundra Shrubs: '148 print ' Old: ', self.ATTM_Shrubs_WT_O[element]149 print ', Wetland Tundra Urban: '150 print ', Old: ', self.ATTM_Urban_WT[element]151 print ' '152 print ' Wetland Tundra Coastal Waters: '153 print ' Old: ', self.ATTM_CoastalWaters_WT_O[element]154 print ' Wetland Tundra Drained Slopes: '155 print ' Young: ', self.ATTM_DrainedSlope_WT_Y[element]156 print ' Medium: ', self.ATTM_DrainedSlope_WT_M[element]157 print ' Old: ', self.ATTM_DrainedSlope_WT_O[element]158 print ' Wetland Tundra No Data: '159 print ' Old: ', self.ATTM_NoData_WT_O[element]160 print ' Wetland Tundra Sand Dunes: '161 print ' Young: ', self.ATTM_SandDunes_WT_Y[element]162 print ' Medium: ', self.ATTM_SandDunes_WT_M[element]163 print ' Old: ', self.ATTM_SandDunes_WT_O[element]164 print ' Wetland Tundra Saturated Barrens: '165 print ' Young: ', self.ATTM_SaturatedBarrens_WT_Y[element]166 print ', Medium: ', self.ATTM_SaturatedBarrens_WT_M[element]167 print ', Old: ', self.ATTM_SaturatedBarrens_WT_O[element]168 169 170# print ' Wet_NPG: ', self.ATTM_Wet_NPG[element]171# print ' Wet_LCP: ', self.ATTM_Wet_LCP[element]172# print ' Wet_CLC: ', self.ATTM_Wet_CLC[element]173# print ' Wet_FCP: ', self.ATTM_Wet_FCP[element]174# print ' Wet_HCP: ', self.ATTM_Wet_HCP[element]175# print ' Lakes: ', self.ATTM_Lakes[element]176# print ' Ponds: ', self.ATTM_Ponds[element]177# print ' Rivers: ', self.ATTM_Rivers[element]178# print ' Urban: ', self.ATTM_Urban[element]179# print ' '180# print ' Gra_NPG: ', self.ATTM_Gra_NPG[element]181# print ' Gra_LCP: ', self.ATTM_Gra_LCP[element]182# print ' Gra_FCP: ', self.ATTM_Gra_FCP[element]183# print ' Gra_HCP: ', self.ATTM_Gra_HCP[element]184# print ' Shr_NPG: ', self.ATTM_Shr_NPG[element]185# print ' Shr_LCP: ', self.ATTM_Shr_LCP[element]186# print ' Shr_FCP: ', self.ATTM_Shr_FCP[element]187# print ' Shr_HCP: ', self.ATTM_Shr_HCP[element]188 exit()189 190 if round(fraction_end, 4) > 1.0 :191 print 'There is a mass balance problem in element ', element192 print 'has a total fractional area greater than 1.0'193 print ' '194 print ' Wetland Tundra Meadows:'195 print ' Young: ', self.ATTM_Meadow_WT_Y[element]196 print ' Medium: ', self.ATTM_Meadow_WT_M[element]197 print ' Old: ', self.ATTM_Meadow_WT_O[element]198 print ' Wetland Tundra Low Center Polygons:'199 print ' Young: ', self.ATTM_LCP_WT_Y[element]200 print ' Medium: ', self.ATTM_LCP_WT_M[element]201 print ' Old: ', self.ATTM_LCP_WT_O[element]202 print ' Wetland Tundra Coalescent Low Center Polygons:'203 print ' Young: ', self.ATTM_CLC_WT_Y[element]204 print ' Medium: ', self.ATTM_CLC_WT_M[element]205 print ' Old: ', self.ATTM_CLC_WT_O[element]206 print ' Wetland Tundra Flat Center Polygons:'207 print ' Young: ', self.ATTM_FCP_WT_Y[element]208 print ' Medium: ', self.ATTM_FCP_WT_M[element]209 print ' Old: ', self.ATTM_FCP_WT_O[element]210 print ' Wetland Tundra High Center Polygons: '211 print ' Young: ', self.ATTM_HCP_WT_Y[element]212 print ' Medium: ', self.ATTM_HCP_WT_M[element]213 print ' Old: ', self.ATTM_HCP_WT_O[element]214 print ' Wetland Tundra Large Lakes: '215 print ' Young: ', self.ATTM_LargeLakes_WT_Y[element]216 print ' Medium: ', self.ATTM_LargeLakes_WT_M[element]217 print ' Old: ', self.ATTM_LargeLakes_WT_O[element]218 print ' Wetland Tundra Medium Lakes: '219 print ' Young: ', self.ATTM_MediumLakes_WT_Y[element]220 print ' Medium: ', self.ATTM_MediumLakes_WT_M[element]221 print ' Old; ', self.ATTM_MediumLakes_WT_O[element]222 print ' Wetland Tundra Small Lakes: '223 print ' Young: ', self.ATTM_SmallLakes_WT_Y[element]224 print ' Medium: ', self.ATTM_SmallLakes_WT_M[element]225 print ' Old: ', self.ATTM_SmallLakes_WT_O[element]226 print ' Wetland Tundra Ponds: '227 print ' Young: ', self.ATTM_Ponds_WT_Y[element]228 print ', Medium: ', self.ATTM_Ponds_WT_M[element]229 print ', Old: ', self.ATTM_Ponds_WT_O[element]230 print ', Wetland Tundra Rivers: '231 print ', Young: ', self.ATTM_Rivers_WT_Y[element]232 print ', Medium: ', self.ATTM_Rivers_WT_M[element]233 print ', Old: ', self.ATTM_Rivers_WT_O[element]234 print ', Wetland Tundra Shrubs: '235 print ' Old: ', self.ATTM_Shrubs_WT_O[element]236 print ', Wetland Tundra Urban: '237 print ', Old: ', self.ATTM_Urban_WT[element]238 print ' '239 print ' Wetland Tundra Coastal Waters: '240 print ' Old: ', self.ATTM_CoastalWaters_WT_O[element]241 print ' Wetland Tundra Drained Slopes: '242 print ' Young: ', self.ATTM_DrainedSlope_WT_Y[element]243 print ' Medium: ', self.ATTM_DrainedSlope_WT_M[element]244 print ' Old: ', self.ATTM_DrainedSlope_WT_O[element]245 print ' Wetland Tundra No Data: '246 print ' Old: ', self.ATTM_NoData_WT_O[element]247 print ' Wetland Tundra Sand Dunes: '248 print ' Young: ', self.ATTM_SandDunes_WT_Y[element]249 print ' Medium: ', self.ATTM_SandDunes_WT_M[element]250 print ' Old: ', self.ATTM_SandDunes_WT_O[element]251 print ' Wetland Tundra Saturated Barrens: '252 print ' Young: ', self.ATTM_SaturatedBarrens_WT_Y[element]253 print ', Medium: ', self.ATTM_SaturatedBarrens_WT_M[element]254 print ', Old: ', self.ATTM_SaturatedBarrens_WT_O[element] 255# print 'Wetland Non-polygonal Ground: ', self.ATTM_Wet_NPG[element]256# print 'Wetland Low Center Polygon: ', self.ATTM_Wet_LCP[element]257# print 'Wetland Coalescent Low Center Polygon: ', self.ATTM_Wet_CLC[element]258# print 'Wetland Flat Center Polygon: ', self.ATTM_Wet_FCP[element]259# print 'Wetland High Center Polygon: ', self.ATTM_Wet_HCP[element]260# print 'Lakes: ' , self.ATTM_Lakes[element]261# print 'Ponds: ', self.ATTM_Ponds[element]262# print 'Rivers: ', self.ATTM_Rivers[element]263# print 'Urban: ', self.ATTM_Urban[element]264 print 'Total: ', np.float64(fraction_end)265 exit()266 if round(fraction_end, 4) < 0.0 :267 print 'There is a mass balance problem in element ', element268 print 'has a total fractional area less than 0.0 '269 print ' '270 print ' Wetland Tundra Meadows:'271 print ' Young: ', self.ATTM_Meadow_WT_Y[element]272 print ' Medium: ', self.ATTM_Meadow_WT_M[element]273 print ' Old: ', self.ATTM_Meadow_WT_O[element]274 print ' Wetland Tundra Low Center Polygons:'275 print ' Young: ', self.ATTM_LCP_WT_Y[element]276 print ' Medium: ', self.ATTM_LCP_WT_M[element]277 print ' Old: ', self.ATTM_LCP_WT_O[element]278 print ' Wetland Tundra Coalescent Low Center Polygons:'279 print ' Young: ', self.ATTM_CLC_WT_Y[element]280 print ' Medium: ', self.ATTM_CLC_WT_M[element]281 print ' Old: ', self.ATTM_CLC_WT_O[element]282 print ' Wetland Tundra Flat Center Polygons:'283 print ' Young: ', self.ATTM_FCP_WT_Y[element]284 print ' Medium: ', self.ATTM_FCP_WT_M[element]285 print ' Old: ', self.ATTM_FCP_WT_O[element]286 print ' Wetland Tundra High Center Polygons: '287 print ' Young: ', self.ATTM_HCP_WT_Y[element]288 print ' Medium: ', self.ATTM_HCP_WT_M[element]289 print ' Old: ', self.ATTM_HCP_WT_O[element]290 print ' Wetland Tundra Large Lakes: '291 print ' Young: ', self.ATTM_LargeLakes_WT_Y[element]292 print ' Medium: ', self.ATTM_LargeLakes_WT_M[element]293 print ' Old: ', self.ATTM_LargeLakes_WT_O[element]294 print ' Wetland Tundra Medium Lakes: '295 print ' Young: ', self.ATTM_MediumLakes_WT_Y[element]296 print ' Medium: ', self.ATTM_MediumLakes_WT_M[element]297 print ' Old; ', self.ATTM_MediumLakes_WT_O[element]298 print ' Wetland Tundra Small Lakes: '299 print ' Young: ', self.ATTM_SmallLakes_WT_Y[element]300 print ' Medium: ', self.ATTM_SmallLakes_WT_M[element]301 print ' Old: ', self.ATTM_SmallLakes_WT_O[element]302 print ' Wetland Tundra Ponds: '303 print ' Young: ', self.ATTM_Ponds_WT_Y[element]304 print ', Medium: ', self.ATTM_Ponds_WT_M[element]305 print ', Old: ', self.ATTM_Ponds_WT_O[element]306 print ', Wetland Tundra Rivers: '307 print ', Young: ', self.ATTM_Rivers_WT_Y[element]308 print ', Medium: ', self.ATTM_Rivers_WT_M[element]309 print ', Old: ', self.ATTM_Rivers_WT_O[element]310 print ', Wetland Tundra Shrubs: '311 print ' Old: ', self.ATTM_Shrubs_WT_O[element]312 print ', Wetland Tundra Urban: '313 print ', Old: ', self.ATTM_Urban_WT[element]314 print ' '315 print ' Wetland Tundra Coastal Waters: '316 print ' Old: ', self.ATTM_CoastalWaters_WT_O[element]317 print ' Wetland Tundra Drained Slopes: '318 print ' Young: ', self.ATTM_DrainedSlope_WT_Y[element]319 print ' Medium: ', self.ATTM_DrainedSlope_WT_M[element]320 print ' Old: ', self.ATTM_DrainedSlope_WT_O[element]321 print ' Wetland Tundra No Data: '322 print ' Old: ', self.ATTM_NoData_WT_O[element]323 print ' Wetland Tundra Sand Dunes: '324 print ' Young: ', self.ATTM_SandDunes_WT_Y[element]325 print ' Medium: ', self.ATTM_SandDunes_WT_M[element]326 print ' Old: ', self.ATTM_SandDunes_WT_O[element]327 print ' Wetland Tundra Saturated Barrens: '328 print ' Young: ', self.ATTM_SaturatedBarrens_WT_Y[element]329 print ', Medium: ', self.ATTM_SaturatedBarrens_WT_M[element]330 print ', Old: ', self.ATTM_SaturatedBarrens_WT_O[element] 331# print 'Wetland Non-polygonal Ground: ', self.ATTM_Wet_NPG[element]332# print 'Wetland Low Center Polygon: ', self.ATTM_Wet_LCP[element]333# print 'Wetland Coalescent Low Center Polygon: ', self.ATTM_Wet_CLC[element]334# print 'Wetland Flat Center Polygon: ', self.ATTM_Wet_FCP[element]335# print 'Wetland High Center Polygon: ', self.ATTM_Wet_HCP[element]336# print 'Lakes: ' , self.ATTM_Lakes[element]337# print 'Ponds: ', self.ATTM_Ponds[element]338# print 'Rivers: ', self.ATTM_Rivers[element]339# print 'Urban: ', self.ATTM_Urban[element]340 print 'Total: ', np.float64(fraction_end)...

Full Screen

Full Screen

mkv.py

Source:mkv.py Github

copy

Full Screen

...35 segment = segments[0]36 # get and recursively parse the SeekHead element37 logger.info('Reading SeekHead element')38 stream.seek(segment.position)39 seek_head = ebml.parse_element(stream, specs)40 if seek_head.name != 'SeekHead':41 raise MalformedMKVError('No SeekHead found')42 seek_head.load(stream, specs, ignore_element_names=['Void', 'CRC-32'])43 self._parse_seekhead(seek_head, segment, stream, specs)44 except ParserError as e:45 raise MalformedMKVError('Parsing error: %s' % e)46 def _parse_seekhead(self, seek_head, segment, stream, specs):47 for seek in seek_head:48 element_id = ebml.read_element_id(seek['SeekID'].data)49 element_name = specs[element_id][1]50 element_position = seek['SeekPosition'].data + segment.position51 if element_position in self._parsed_positions:52 logger.warning('Skipping already parsed %s element at position %d', element_name, element_position)53 continue54 if element_name == 'Info':55 logger.info('Processing element %s from SeekHead at position %d', element_name, element_position)56 stream.seek(element_position)57 self.info = Info.fromelement(ebml.parse_element(stream, specs, True, ignore_element_names=['Void', 'CRC-32']))58 elif element_name == 'Tracks':59 logger.info('Processing element %s from SeekHead at position %d', element_name, element_position)60 stream.seek(element_position)61 tracks = ebml.parse_element(stream, specs, True, ignore_element_names=['Void', 'CRC-32'])62 self.video_tracks.extend([VideoTrack.fromelement(t) for t in tracks if t['TrackType'].data == VIDEO_TRACK])63 self.audio_tracks.extend([AudioTrack.fromelement(t) for t in tracks if t['TrackType'].data == AUDIO_TRACK])64 self.subtitle_tracks.extend([SubtitleTrack.fromelement(t) for t in tracks if t['TrackType'].data == SUBTITLE_TRACK])65 elif element_name == 'Chapters':66 logger.info('Processing element %s from SeekHead at position %d', element_name, element_position)67 stream.seek(element_position)68 self.chapters.extend([Chapter.fromelement(c) for c in ebml.parse_element(stream, specs, True, ignore_element_names=['Void', 'CRC-32'])[0] if c.name == 'ChapterAtom'])69 elif element_name == 'Tags':70 logger.info('Processing element %s from SeekHead at position %d', element_name, element_position)71 stream.seek(element_position)72 self.tags.extend([Tag.fromelement(t) for t in ebml.parse_element(stream, specs, True, ignore_element_names=['Void', 'CRC-32'])])73 elif element_name == 'SeekHead' and self.recurse_seek_head:74 logger.info('Processing element %s from SeekHead at position %d', element_name, element_position)75 stream.seek(element_position)76 self._parse_seekhead(ebml.parse_element(stream, specs, True, ignore_element_names=['Void', 'CRC-32']), segment, stream, specs)77 else:78 logger.debug('Element %s ignored', element_name)79 self._parsed_positions.add(element_position)80 def to_dict(self):81 return {'info': self.info.__dict__, 'video_tracks': [t.__dict__ for t in self.video_tracks],82 'audio_tracks': [t.__dict__ for t in self.audio_tracks], 'subtitle_tracks': [t.__dict__ for t in self.subtitle_tracks],83 'chapters': [c.__dict__ for c in self.chapters], 'tags': [t.__dict__ for t in self.tags]}84 def __repr__(self):85 return '<%s [%r, %r, %r, %r]>' % (self.__class__.__name__, self.info, self.video_tracks, self.audio_tracks, self.subtitle_tracks)86class Info(object):87 """Object for the Info EBML element"""88 def __init__(self, title=None, duration=None, date_utc=None, timecode_scale=None, muxing_app=None, writing_app=None):89 self.title = title90 self.duration = timedelta(microseconds=duration * (timecode_scale or 1000000) // 1000) if duration else None91 self.date_utc = date_utc92 self.muxing_app = muxing_app93 self.writing_app = writing_app94 @classmethod95 def fromelement(cls, element):96 """Load the :class:`Info` from an :class:`~enzyme.parsers.ebml.Element`97 :param element: the Info element98 :type element: :class:`~enzyme.parsers.ebml.Element`99 """100 title = element.get('Title')101 duration = element.get('Duration')102 date_utc = element.get('DateUTC')103 timecode_scale = element.get('TimecodeScale')104 muxing_app = element.get('MuxingApp')105 writing_app = element.get('WritingApp')106 return cls(title, duration, date_utc, timecode_scale, muxing_app, writing_app)107 def __repr__(self):108 return '<%s [title=%r, duration=%s, date=%s]>' % (self.__class__.__name__, self.title, self.duration, self.date_utc)109 def __str__(self):110 return repr(self.__dict__)111class Track(object):112 """Base object for the Tracks EBML element"""113 def __init__(self, type=None, number=None, name=None, language=None, enabled=None, default=None, forced=None, lacing=None, # @ReservedAssignment114 codec_id=None, codec_name=None):115 self.type = type116 self.number = number117 self.name = name118 self.language = language119 self.enabled = enabled120 self.default = default121 self.forced = forced122 self.lacing = lacing123 self.codec_id = codec_id124 self.codec_name = codec_name125 @classmethod126 def fromelement(cls, element):127 """Load the :class:`Track` from an :class:`~enzyme.parsers.ebml.Element`128 :param element: the Track element129 :type element: :class:`~enzyme.parsers.ebml.Element`130 """131 type = element.get('TrackType') # @ReservedAssignment132 number = element.get('TrackNumber', 0)133 name = element.get('Name')134 language = element.get('Language')135 enabled = bool(element.get('FlagEnabled', 1))136 default = bool(element.get('FlagDefault', 1))137 forced = bool(element.get('FlagForced', 0))138 lacing = bool(element.get('FlagLacing', 1))139 codec_id = element.get('CodecID')140 codec_name = element.get('CodecName')141 return cls(type=type, number=number, name=name, language=language, enabled=enabled, default=default,142 forced=forced, lacing=lacing, codec_id=codec_id, codec_name=codec_name)143 def __repr__(self):144 return '<%s [%d, name=%r, language=%s]>' % (self.__class__.__name__, self.number, self.name, self.language)145 def __str__(self):146 return str(self.__dict__)147class VideoTrack(Track):148 """Object for the Tracks EBML element with :data:`VIDEO_TRACK` TrackType"""149 def __init__(self, width=0, height=0, interlaced=False, stereo_mode=None, crop=None,150 display_width=None, display_height=None, display_unit=None, aspect_ratio_type=None, **kwargs):151 super(VideoTrack, self).__init__(**kwargs)152 self.width = width153 self.height = height154 self.interlaced = interlaced155 self.stereo_mode = stereo_mode156 self.crop = crop157 self.display_width = display_width158 self.display_height = display_height159 self.display_unit = display_unit160 self.aspect_ratio_type = aspect_ratio_type161 @classmethod162 def fromelement(cls, element):163 """Load the :class:`VideoTrack` from an :class:`~enzyme.parsers.ebml.Element`164 :param element: the Track element with :data:`VIDEO_TRACK` TrackType165 :type element: :class:`~enzyme.parsers.ebml.Element`166 """167 videotrack = super(VideoTrack, cls).fromelement(element)168 videotrack.width = element['Video'].get('PixelWidth', 0)169 videotrack.height = element['Video'].get('PixelHeight', 0)170 videotrack.interlaced = bool(element['Video'].get('FlagInterlaced', False))171 videotrack.stereo_mode = element['Video'].get('StereoMode')172 videotrack.crop = {}173 if 'PixelCropTop' in element['Video']:174 videotrack.crop['top'] = element['Video']['PixelCropTop']175 if 'PixelCropBottom' in element['Video']:176 videotrack.crop['bottom'] = element['Video']['PixelCropBottom']177 if 'PixelCropLeft' in element['Video']:178 videotrack.crop['left'] = element['Video']['PixelCropLeft']179 if 'PixelCropRight' in element['Video']:180 videotrack.crop['right'] = element['Video']['PixelCropRight']181 videotrack.display_width = element['Video'].get('DisplayWidth')182 videotrack.display_height = element['Video'].get('DisplayHeight')183 videotrack.display_unit = element['Video'].get('DisplayUnit')184 videotrack.aspect_ratio_type = element['Video'].get('AspectRatioType')185 return videotrack186 def __repr__(self):187 return '<%s [%d, %dx%d, %s, name=%r, language=%s]>' % (self.__class__.__name__, self.number, self.width, self.height,188 self.codec_id, self.name, self.language)189 def __str__(self):190 return str(self.__dict__)191class AudioTrack(Track):192 """Object for the Tracks EBML element with :data:`AUDIO_TRACK` TrackType"""193 def __init__(self, sampling_frequency=None, channels=None, output_sampling_frequency=None, bit_depth=None, **kwargs):194 super(AudioTrack, self).__init__(**kwargs)195 self.sampling_frequency = sampling_frequency196 self.channels = channels197 self.output_sampling_frequency = output_sampling_frequency198 self.bit_depth = bit_depth199 @classmethod200 def fromelement(cls, element):201 """Load the :class:`AudioTrack` from an :class:`~enzyme.parsers.ebml.Element`202 :param element: the Track element with :data:`AUDIO_TRACK` TrackType203 :type element: :class:`~enzyme.parsers.ebml.Element`204 """205 audiotrack = super(AudioTrack, cls).fromelement(element)206 audiotrack.sampling_frequency = element['Audio'].get('SamplingFrequency', 8000.0)207 audiotrack.channels = element['Audio'].get('Channels', 1)208 audiotrack.output_sampling_frequency = element['Audio'].get('OutputSamplingFrequency')209 audiotrack.bit_depth = element['Audio'].get('BitDepth')210 return audiotrack211 def __repr__(self):212 return '<%s [%d, %d channel(s), %.0fHz, %s, name=%r, language=%s]>' % (self.__class__.__name__, self.number, self.channels,213 self.sampling_frequency, self.codec_id, self.name, self.language)214class SubtitleTrack(Track):215 """Object for the Tracks EBML element with :data:`SUBTITLE_TRACK` TrackType"""216 pass217class Tag(object):218 """Object for the Tag EBML element"""219 def __init__(self, targets=None, simpletags=None):220 self.targets = targets if targets is not None else []221 self.simpletags = simpletags if simpletags is not None else []222 @classmethod223 def fromelement(cls, element):224 """Load the :class:`Tag` from an :class:`~enzyme.parsers.ebml.Element`225 :param element: the Tag element226 :type element: :class:`~enzyme.parsers.ebml.Element`227 """228 targets = element['Targets'] if 'Targets' in element else []229 simpletags = [SimpleTag.fromelement(s) for s in element if s.name == 'SimpleTag']230 return cls(targets, simpletags)231 def __repr__(self):232 return '<%s [targets=%r, simpletags=%r]>' % (self.__class__.__name__, self.targets, self.simpletags)233class SimpleTag(object):234 """Object for the SimpleTag EBML element"""235 def __init__(self, name, language='und', default=True, string=None, binary=None):236 self.name = name237 self.language = language238 self.default = default239 self.string = string240 self.binary = binary241 @classmethod242 def fromelement(cls, element):243 """Load the :class:`SimpleTag` from an :class:`~enzyme.parsers.ebml.Element`244 :param element: the SimpleTag element245 :type element: :class:`~enzyme.parsers.ebml.Element`246 """247 name = element.get('TagName')248 language = element.get('TagLanguage', 'und')249 default = element.get('TagDefault', True)250 string = element.get('TagString')251 binary = element.get('TagBinary')252 return cls(name, language, default, string, binary)253 def __repr__(self):254 return '<%s [%s, language=%s, default=%s, string=%s]>' % (self.__class__.__name__, self.name, self.language, self.default, self.string)255class Chapter(object):256 """Object for the ChapterAtom and ChapterDisplay EBML element257 .. note::258 For the sake of simplicity, it is assumed that the ChapterAtom element259 has no more than 1 ChapterDisplay child element and informations it contains260 are merged into the :class:`Chapter`261 """262 def __init__(self, start, hidden=False, enabled=False, end=None, string=None, language=None):263 self.start = start264 self.hidden = hidden265 self.enabled = enabled266 self.end = end267 self.string = string268 self.language = language269 @classmethod270 def fromelement(cls, element):271 """Load the :class:`Chapter` from an :class:`~enzyme.parsers.ebml.Element`272 :param element: the ChapterAtom element273 :type element: :class:`~enzyme.parsers.ebml.Element`274 """275 start = timedelta(microseconds=element.get('ChapterTimeStart') // 1000)276 hidden = element.get('ChapterFlagHidden', False)277 enabled = element.get('ChapterFlagEnabled', True)278 end = element.get('ChapterTimeEnd')279 chapterdisplays = [c for c in element if c.name == 'ChapterDisplay']280 if len(chapterdisplays) > 1:281 logger.warning('More than 1 (%d) ChapterDisplay element in the ChapterAtom, using the first one', len(chapterdisplays))282 if chapterdisplays:283 string = chapterdisplays[0].get('ChapString')284 language = chapterdisplays[0].get('ChapLanguage')...

Full Screen

Full Screen

etree_lxml.py

Source:etree_lxml.py Github

copy

Full Screen

1"""Module for supporting the lxml.etree library. The idea here is to use as much2of the native library as possible, without using fragile hacks like custom element3names that break between releases. The downside of this is that we cannot represent4all possible trees; specifically the following are known to cause problems:5Text or comments as siblings of the root element6Docypes with no name7When any of these things occur, we emit a DataLossWarning8"""9from __future__ import absolute_import, division, unicode_literals10import warnings11import re12import sys13from . import _base14from ..constants import DataLossWarning15from .. import constants16from . import etree as etree_builders17from .. import ihatexml18import lxml.etree as etree19fullTree = True20tag_regexp = re.compile("{([^}]*)}(.*)")21comment_type = etree.Comment("asd").tag22class DocumentType(object):23 def __init__(self, name, publicId, systemId):24 self.name = name25 self.publicId = publicId26 self.systemId = systemId27class Document(object):28 def __init__(self):29 self._elementTree = None30 self._childNodes = []31 def appendChild(self, element):32 self._elementTree.getroot().addnext(element._element)33 def _getChildNodes(self):34 return self._childNodes35 childNodes = property(_getChildNodes)36def testSerializer(element):37 rv = []38 finalText = None39 infosetFilter = ihatexml.InfosetFilter()40 def serializeElement(element, indent=0):41 if not hasattr(element, "tag"):42 if hasattr(element, "getroot"):43 # Full tree case44 rv.append("#document")45 if element.docinfo.internalDTD:46 if not (element.docinfo.public_id or47 element.docinfo.system_url):48 dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name49 else:50 dtd_str = """<!DOCTYPE %s "%s" "%s">""" % (51 element.docinfo.root_name,52 element.docinfo.public_id,53 element.docinfo.system_url)54 rv.append("|%s%s" % (' ' * (indent + 2), dtd_str))55 next_element = element.getroot()56 while next_element.getprevious() is not None:57 next_element = next_element.getprevious()58 while next_element is not None:59 serializeElement(next_element, indent + 2)60 next_element = next_element.getnext()61 elif isinstance(element, str) or isinstance(element, bytes):62 # Text in a fragment63 assert isinstance(element, str) or sys.version_info.major == 264 rv.append("|%s\"%s\"" % (' ' * indent, element))65 else:66 # Fragment case67 rv.append("#document-fragment")68 for next_element in element:69 serializeElement(next_element, indent + 2)70 elif element.tag == comment_type:71 rv.append("|%s<!-- %s -->" % (' ' * indent, element.text))72 if hasattr(element, "tail") and element.tail:73 rv.append("|%s\"%s\"" % (' ' * indent, element.tail))74 else:75 assert isinstance(element, etree._Element)76 nsmatch = etree_builders.tag_regexp.match(element.tag)77 if nsmatch is not None:78 ns = nsmatch.group(1)79 tag = nsmatch.group(2)80 prefix = constants.prefixes[ns]81 rv.append("|%s<%s %s>" % (' ' * indent, prefix,82 infosetFilter.fromXmlName(tag)))83 else:84 rv.append("|%s<%s>" % (' ' * indent,85 infosetFilter.fromXmlName(element.tag)))86 if hasattr(element, "attrib"):87 attributes = []88 for name, value in element.attrib.items():89 nsmatch = tag_regexp.match(name)90 if nsmatch is not None:91 ns, name = nsmatch.groups()92 name = infosetFilter.fromXmlName(name)93 prefix = constants.prefixes[ns]94 attr_string = "%s %s" % (prefix, name)95 else:96 attr_string = infosetFilter.fromXmlName(name)97 attributes.append((attr_string, value))98 for name, value in sorted(attributes):99 rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value))100 if element.text:101 rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text))102 indent += 2103 for child in element:104 serializeElement(child, indent)105 if hasattr(element, "tail") and element.tail:106 rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail))107 serializeElement(element, 0)108 if finalText is not None:109 rv.append("|%s\"%s\"" % (' ' * 2, finalText))110 return "\n".join(rv)111def tostring(element):112 """Serialize an element and its child nodes to a string"""113 rv = []114 finalText = None115 def serializeElement(element):116 if not hasattr(element, "tag"):117 if element.docinfo.internalDTD:118 if element.docinfo.doctype:119 dtd_str = element.docinfo.doctype120 else:121 dtd_str = "<!DOCTYPE %s>" % element.docinfo.root_name122 rv.append(dtd_str)123 serializeElement(element.getroot())124 elif element.tag == comment_type:125 rv.append("<!--%s-->" % (element.text,))126 else:127 # This is assumed to be an ordinary element128 if not element.attrib:129 rv.append("<%s>" % (element.tag,))130 else:131 attr = " ".join(["%s=\"%s\"" % (name, value)132 for name, value in element.attrib.items()])133 rv.append("<%s %s>" % (element.tag, attr))134 if element.text:135 rv.append(element.text)136 for child in element:137 serializeElement(child)138 rv.append("</%s>" % (element.tag,))139 if hasattr(element, "tail") and element.tail:140 rv.append(element.tail)141 serializeElement(element)142 if finalText is not None:143 rv.append("%s\"" % (' ' * 2, finalText))144 return "".join(rv)145class TreeBuilder(_base.TreeBuilder):146 documentClass = Document147 doctypeClass = DocumentType148 elementClass = None149 commentClass = None150 fragmentClass = Document151 implementation = etree152 def __init__(self, namespaceHTMLElements, fullTree=False):153 builder = etree_builders.getETreeModule(etree, fullTree=fullTree)154 infosetFilter = self.infosetFilter = ihatexml.InfosetFilter()155 self.namespaceHTMLElements = namespaceHTMLElements156 class Attributes(dict):157 def __init__(self, element, value={}):158 self._element = element159 dict.__init__(self, value)160 for key, value in self.items():161 if isinstance(key, tuple):162 name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1]))163 else:164 name = infosetFilter.coerceAttribute(key)165 self._element._element.attrib[name] = value166 def __setitem__(self, key, value):167 dict.__setitem__(self, key, value)168 if isinstance(key, tuple):169 name = "{%s}%s" % (key[2], infosetFilter.coerceAttribute(key[1]))170 else:171 name = infosetFilter.coerceAttribute(key)172 self._element._element.attrib[name] = value173 class Element(builder.Element):174 def __init__(self, name, namespace):175 name = infosetFilter.coerceElement(name)176 builder.Element.__init__(self, name, namespace=namespace)177 self._attributes = Attributes(self)178 def _setName(self, name):179 self._name = infosetFilter.coerceElement(name)180 self._element.tag = self._getETreeTag(181 self._name, self._namespace)182 def _getName(self):183 return infosetFilter.fromXmlName(self._name)184 name = property(_getName, _setName)185 def _getAttributes(self):186 return self._attributes187 def _setAttributes(self, attributes):188 self._attributes = Attributes(self, attributes)189 attributes = property(_getAttributes, _setAttributes)190 def insertText(self, data, insertBefore=None):191 data = infosetFilter.coerceCharacters(data)192 builder.Element.insertText(self, data, insertBefore)193 def appendChild(self, child):194 builder.Element.appendChild(self, child)195 class Comment(builder.Comment):196 def __init__(self, data):197 data = infosetFilter.coerceComment(data)198 builder.Comment.__init__(self, data)199 def _setData(self, data):200 data = infosetFilter.coerceComment(data)201 self._element.text = data202 def _getData(self):203 return self._element.text204 data = property(_getData, _setData)205 self.elementClass = Element206 self.commentClass = builder.Comment207 # self.fragmentClass = builder.DocumentFragment208 _base.TreeBuilder.__init__(self, namespaceHTMLElements)209 def reset(self):210 _base.TreeBuilder.reset(self)211 self.insertComment = self.insertCommentInitial212 self.initial_comments = []213 self.doctype = None214 def testSerializer(self, element):215 return testSerializer(element)216 def getDocument(self):217 if fullTree:218 return self.document._elementTree219 else:220 return self.document._elementTree.getroot()221 def getFragment(self):222 fragment = []223 element = self.openElements[0]._element224 if element.text:225 fragment.append(element.text)226 fragment.extend(list(element))227 if element.tail:228 fragment.append(element.tail)229 return fragment230 def insertDoctype(self, token):231 name = token["name"]232 publicId = token["publicId"]233 systemId = token["systemId"]234 if not name:235 warnings.warn("lxml cannot represent empty doctype", DataLossWarning)236 self.doctype = None237 else:238 coercedName = self.infosetFilter.coerceElement(name)239 if coercedName != name:240 warnings.warn("lxml cannot represent non-xml doctype", DataLossWarning)241 doctype = self.doctypeClass(coercedName, publicId, systemId)242 self.doctype = doctype243 def insertCommentInitial(self, data, parent=None):244 self.initial_comments.append(data)245 def insertCommentMain(self, data, parent=None):246 if (parent == self.document and247 self.document._elementTree.getroot()[-1].tag == comment_type):248 warnings.warn("lxml cannot represent adjacent comments beyond the root elements", DataLossWarning)249 super(TreeBuilder, self).insertComment(data, parent)250 def insertRoot(self, token):251 """Create the document root"""252 # Because of the way libxml2 works, it doesn't seem to be possible to253 # alter information like the doctype after the tree has been parsed.254 # Therefore we need to use the built-in parser to create our iniial255 # tree, after which we can add elements like normal256 docStr = ""257 if self.doctype:258 assert self.doctype.name259 docStr += "<!DOCTYPE %s" % self.doctype.name260 if (self.doctype.publicId is not None or261 self.doctype.systemId is not None):262 docStr += (' PUBLIC "%s" ' %263 (self.infosetFilter.coercePubid(self.doctype.publicId or "")))264 if self.doctype.systemId:265 sysid = self.doctype.systemId266 if sysid.find("'") >= 0 and sysid.find('"') >= 0:267 warnings.warn("DOCTYPE system cannot contain single and double quotes", DataLossWarning)268 sysid = sysid.replace("'", 'U00027')269 if sysid.find("'") >= 0:270 docStr += '"%s"' % sysid271 else:272 docStr += "'%s'" % sysid273 else:274 docStr += "''"275 docStr += ">"276 if self.doctype.name != token["name"]:277 warnings.warn("lxml cannot represent doctype with a different name to the root element", DataLossWarning)278 docStr += "<THIS_SHOULD_NEVER_APPEAR_PUBLICLY/>"279 root = etree.fromstring(docStr)280 # Append the initial comments:281 for comment_token in self.initial_comments:282 root.addprevious(etree.Comment(comment_token["data"]))283 # Create the root document and add the ElementTree to it284 self.document = self.documentClass()285 self.document._elementTree = root.getroottree()286 # Give the root element the right name287 name = token["name"]288 namespace = token.get("namespace", self.defaultNamespace)289 if namespace is None:290 etree_tag = name291 else:292 etree_tag = "{%s}%s" % (namespace, name)293 root.tag = etree_tag294 # Add the root element to the internal child/open data structures295 root_element = self.elementClass(name, namespace)296 root_element._element = root297 self.document._childNodes.append(root_element)298 self.openElements.append(root_element)299 # Reset to the default insert comment function...

Full Screen

Full Screen

etree.py

Source:etree.py Github

copy

Full Screen

1from __future__ import absolute_import, division, unicode_literals2from six import text_type3import re4from . import _base5from .. import ihatexml6from .. import constants7from ..constants import namespaces8from ..utils import moduleFactoryFactory9tag_regexp = re.compile("{([^}]*)}(.*)")10def getETreeBuilder(ElementTreeImplementation, fullTree=False):11 ElementTree = ElementTreeImplementation12 ElementTreeCommentType = ElementTree.Comment("asd").tag13 class Element(_base.Node):14 def __init__(self, name, namespace=None):15 self._name = name16 self._namespace = namespace17 self._element = ElementTree.Element(self._getETreeTag(name,18 namespace))19 if namespace is None:20 self.nameTuple = namespaces["html"], self._name21 else:22 self.nameTuple = self._namespace, self._name23 self.parent = None24 self._childNodes = []25 self._flags = []26 def _getETreeTag(self, name, namespace):27 if namespace is None:28 etree_tag = name29 else:30 etree_tag = "{%s}%s" % (namespace, name)31 return etree_tag32 def _setName(self, name):33 self._name = name34 self._element.tag = self._getETreeTag(self._name, self._namespace)35 def _getName(self):36 return self._name37 name = property(_getName, _setName)38 def _setNamespace(self, namespace):39 self._namespace = namespace40 self._element.tag = self._getETreeTag(self._name, self._namespace)41 def _getNamespace(self):42 return self._namespace43 namespace = property(_getNamespace, _setNamespace)44 def _getAttributes(self):45 return self._element.attrib46 def _setAttributes(self, attributes):47 # Delete existing attributes first48 # XXX - there may be a better way to do this...49 for key in list(self._element.attrib.keys()):50 del self._element.attrib[key]51 for key, value in attributes.items():52 if isinstance(key, tuple):53 name = "{%s}%s" % (key[2], key[1])54 else:55 name = key56 self._element.set(name, value)57 attributes = property(_getAttributes, _setAttributes)58 def _getChildNodes(self):59 return self._childNodes60 def _setChildNodes(self, value):61 del self._element[:]62 self._childNodes = []63 for element in value:64 self.insertChild(element)65 childNodes = property(_getChildNodes, _setChildNodes)66 def hasContent(self):67 """Return true if the node has children or text"""68 return bool(self._element.text or len(self._element))69 def appendChild(self, node):70 self._childNodes.append(node)71 self._element.append(node._element)72 node.parent = self73 def insertBefore(self, node, refNode):74 index = list(self._element).index(refNode._element)75 self._element.insert(index, node._element)76 node.parent = self77 def removeChild(self, node):78 self._element.remove(node._element)79 node.parent = None80 def insertText(self, data, insertBefore=None):81 if not(len(self._element)):82 if not self._element.text:83 self._element.text = ""84 self._element.text += data85 elif insertBefore is None:86 # Insert the text as the tail of the last child element87 if not self._element[-1].tail:88 self._element[-1].tail = ""89 self._element[-1].tail += data90 else:91 # Insert the text before the specified node92 children = list(self._element)93 index = children.index(insertBefore._element)94 if index > 0:95 if not self._element[index - 1].tail:96 self._element[index - 1].tail = ""97 self._element[index - 1].tail += data98 else:99 if not self._element.text:100 self._element.text = ""101 self._element.text += data102 def cloneNode(self):103 element = type(self)(self.name, self.namespace)104 for name, value in self.attributes.items():105 element.attributes[name] = value106 return element107 def reparentChildren(self, newParent):108 if newParent.childNodes:109 newParent.childNodes[-1]._element.tail += self._element.text110 else:111 if not newParent._element.text:112 newParent._element.text = ""113 if self._element.text is not None:114 newParent._element.text += self._element.text115 self._element.text = ""116 _base.Node.reparentChildren(self, newParent)117 class Comment(Element):118 def __init__(self, data):119 # Use the superclass constructor to set all properties on the120 # wrapper element121 self._element = ElementTree.Comment(data)122 self.parent = None123 self._childNodes = []124 self._flags = []125 def _getData(self):126 return self._element.text127 def _setData(self, value):128 self._element.text = value129 data = property(_getData, _setData)130 class DocumentType(Element):131 def __init__(self, name, publicId, systemId):132 Element.__init__(self, "<!DOCTYPE>")133 self._element.text = name134 self.publicId = publicId135 self.systemId = systemId136 def _getPublicId(self):137 return self._element.get("publicId", "")138 def _setPublicId(self, value):139 if value is not None:140 self._element.set("publicId", value)141 publicId = property(_getPublicId, _setPublicId)142 def _getSystemId(self):143 return self._element.get("systemId", "")144 def _setSystemId(self, value):145 if value is not None:146 self._element.set("systemId", value)147 systemId = property(_getSystemId, _setSystemId)148 class Document(Element):149 def __init__(self):150 Element.__init__(self, "DOCUMENT_ROOT")151 class DocumentFragment(Element):152 def __init__(self):153 Element.__init__(self, "DOCUMENT_FRAGMENT")154 def testSerializer(element):155 rv = []156 def serializeElement(element, indent=0):157 if not(hasattr(element, "tag")):158 element = element.getroot()159 if element.tag == "<!DOCTYPE>":160 if element.get("publicId") or element.get("systemId"):161 publicId = element.get("publicId") or ""162 systemId = element.get("systemId") or ""163 rv.append("""<!DOCTYPE %s "%s" "%s">""" %164 (element.text, publicId, systemId))165 else:166 rv.append("<!DOCTYPE %s>" % (element.text,))167 elif element.tag == "DOCUMENT_ROOT":168 rv.append("#document")169 if element.text is not None:170 rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text))171 if element.tail is not None:172 raise TypeError("Document node cannot have tail")173 if hasattr(element, "attrib") and len(element.attrib):174 raise TypeError("Document node cannot have attributes")175 elif element.tag == ElementTreeCommentType:176 rv.append("|%s<!-- %s -->" % (' ' * indent, element.text))177 else:178 assert isinstance(element.tag, text_type), \179 "Expected unicode, got %s, %s" % (type(element.tag), element.tag)180 nsmatch = tag_regexp.match(element.tag)181 if nsmatch is None:182 name = element.tag183 else:184 ns, name = nsmatch.groups()185 prefix = constants.prefixes[ns]186 name = "%s %s" % (prefix, name)187 rv.append("|%s<%s>" % (' ' * indent, name))188 if hasattr(element, "attrib"):189 attributes = []190 for name, value in element.attrib.items():191 nsmatch = tag_regexp.match(name)192 if nsmatch is not None:193 ns, name = nsmatch.groups()194 prefix = constants.prefixes[ns]195 attr_string = "%s %s" % (prefix, name)196 else:197 attr_string = name198 attributes.append((attr_string, value))199 for name, value in sorted(attributes):200 rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value))201 if element.text:202 rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text))203 indent += 2204 for child in element:205 serializeElement(child, indent)206 if element.tail:207 rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail))208 serializeElement(element, 0)209 return "\n".join(rv)210 def tostring(element):211 """Serialize an element and its child nodes to a string"""212 rv = []213 filter = ihatexml.InfosetFilter()214 def serializeElement(element):215 if isinstance(element, ElementTree.ElementTree):216 element = element.getroot()217 if element.tag == "<!DOCTYPE>":218 if element.get("publicId") or element.get("systemId"):219 publicId = element.get("publicId") or ""220 systemId = element.get("systemId") or ""221 rv.append("""<!DOCTYPE %s PUBLIC "%s" "%s">""" %222 (element.text, publicId, systemId))223 else:224 rv.append("<!DOCTYPE %s>" % (element.text,))225 elif element.tag == "DOCUMENT_ROOT":226 if element.text is not None:227 rv.append(element.text)228 if element.tail is not None:229 raise TypeError("Document node cannot have tail")230 if hasattr(element, "attrib") and len(element.attrib):231 raise TypeError("Document node cannot have attributes")232 for child in element:233 serializeElement(child)234 elif element.tag == ElementTreeCommentType:235 rv.append("<!--%s-->" % (element.text,))236 else:237 # This is assumed to be an ordinary element238 if not element.attrib:239 rv.append("<%s>" % (filter.fromXmlName(element.tag),))240 else:241 attr = " ".join(["%s=\"%s\"" % (242 filter.fromXmlName(name), value)243 for name, value in element.attrib.items()])244 rv.append("<%s %s>" % (element.tag, attr))245 if element.text:246 rv.append(element.text)247 for child in element:248 serializeElement(child)249 rv.append("</%s>" % (element.tag,))250 if element.tail:251 rv.append(element.tail)252 serializeElement(element)253 return "".join(rv)254 class TreeBuilder(_base.TreeBuilder):255 documentClass = Document256 doctypeClass = DocumentType257 elementClass = Element258 commentClass = Comment259 fragmentClass = DocumentFragment260 implementation = ElementTreeImplementation261 def testSerializer(self, element):262 return testSerializer(element)263 def getDocument(self):264 if fullTree:265 return self.document._element266 else:267 if self.defaultNamespace is not None:268 return self.document._element.find(269 "{%s}html" % self.defaultNamespace)270 else:271 return self.document._element.find("html")272 def getFragment(self):273 return _base.TreeBuilder.getFragment(self)._element274 return locals()...

Full Screen

Full Screen

charts.py

Source:charts.py Github

copy

Full Screen

1# coding=UTF-82# Copyright (c) 2010-2011 openpyxl3#4# Permission is hereby granted, free of charge, to any person obtaining a copy5# of this software and associated documentation files (the "Software"), to deal6# in the Software without restriction, including without limitation the rights7# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell8# copies of the Software, and to permit persons to whom the Software is9# furnished to do so, subject to the following conditions:10#11# The above copyright notice and this permission notice shall be included in12# all copies or substantial portions of the Software.13#14# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE17# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,19# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN20# THE SOFTWARE.21#22# @license: http://www.opensource.org/licenses/mit-license.php23# @author: see AUTHORS file2425from openpyxl.shared.xmltools import Element, SubElement, get_document_content26from openpyxl.chart import Chart, ErrorBar2728class ChartWriter(object):2930 def __init__(self, chart):31 self.chart = chart3233 def write(self):34 """ write a chart """3536 root = Element('c:chartSpace',37 {'xmlns:c':"http://schemas.openxmlformats.org/drawingml/2006/chart",38 'xmlns:a':"http://schemas.openxmlformats.org/drawingml/2006/main",39 'xmlns:r':"http://schemas.openxmlformats.org/officeDocument/2006/relationships"})4041 SubElement(root, 'c:lang', {'val':self.chart.lang})42 self._write_chart(root)43 self._write_print_settings(root)44 self._write_shapes(root)4546 return get_document_content(root)4748 def _write_chart(self, root):4950 chart = self.chart5152 ch = SubElement(root, 'c:chart')53 self._write_title(ch)54 plot_area = SubElement(ch, 'c:plotArea')55 layout = SubElement(plot_area, 'c:layout')56 mlayout = SubElement(layout, 'c:manualLayout')57 SubElement(mlayout, 'c:layoutTarget', {'val':'inner'})58 SubElement(mlayout, 'c:xMode', {'val':'edge'})59 SubElement(mlayout, 'c:yMode', {'val':'edge'})60 SubElement(mlayout, 'c:x', {'val':str(chart._get_margin_left())})61 SubElement(mlayout, 'c:y', {'val':str(chart._get_margin_top())})62 SubElement(mlayout, 'c:w', {'val':str(chart.width)})63 SubElement(mlayout, 'c:h', {'val':str(chart.height)})6465 if chart.type == Chart.SCATTER_CHART:66 subchart = SubElement(plot_area, 'c:scatterChart')67 SubElement(subchart, 'c:scatterStyle', {'val':str('lineMarker')})68 else:69 if chart.type == Chart.BAR_CHART:70 subchart = SubElement(plot_area, 'c:barChart')71 SubElement(subchart, 'c:barDir', {'val':'col'})72 else:73 subchart = SubElement(plot_area, 'c:lineChart')7475 SubElement(subchart, 'c:grouping', {'val':chart.grouping})7677 self._write_series(subchart)7879 SubElement(subchart, 'c:marker', {'val':'1'})80 SubElement(subchart, 'c:axId', {'val':str(chart.x_axis.id)})81 SubElement(subchart, 'c:axId', {'val':str(chart.y_axis.id)})8283 if chart.type == Chart.SCATTER_CHART:84 self._write_axis(plot_area, chart.x_axis, 'c:valAx')85 else:86 self._write_axis(plot_area, chart.x_axis, 'c:catAx')87 self._write_axis(plot_area, chart.y_axis, 'c:valAx')8889 self._write_legend(ch)9091 SubElement(ch, 'c:plotVisOnly', {'val':'1'})9293 def _write_title(self, chart):94 if self.chart.title != '':95 title = SubElement(chart, 'c:title')96 tx = SubElement(title, 'c:tx')97 rich = SubElement(tx, 'c:rich')98 SubElement(rich, 'a:bodyPr')99 SubElement(rich, 'a:lstStyle')100 p = SubElement(rich, 'a:p')101 pPr = SubElement(p, 'a:pPr')102 SubElement(pPr, 'a:defRPr')103 r = SubElement(p, 'a:r')104 SubElement(r, 'a:rPr', {'lang':self.chart.lang})105 t = SubElement(r, 'a:t').text = self.chart.title106 SubElement(title, 'c:layout')107108 def _write_axis(self, plot_area, axis, label):109110 ax = SubElement(plot_area, label)111 SubElement(ax, 'c:axId', {'val':str(axis.id)})112113 scaling = SubElement(ax, 'c:scaling')114 SubElement(scaling, 'c:orientation', {'val':axis.orientation})115 if label == 'c:valAx':116 SubElement(scaling, 'c:max', {'val':str(axis.max)})117 SubElement(scaling, 'c:min', {'val':str(axis.min)})118119 SubElement(ax, 'c:axPos', {'val':axis.position})120 if label == 'c:valAx':121 SubElement(ax, 'c:majorGridlines')122 SubElement(ax, 'c:numFmt', {'formatCode':"General", 'sourceLinked':'1'})123 if axis.title != '':124 title = SubElement(ax, 'c:title')125 tx = SubElement(title, 'c:tx')126 rich = SubElement(tx, 'c:rich')127 SubElement(rich, 'a:bodyPr')128 SubElement(rich, 'a:lstStyle')129 p = SubElement(rich, 'a:p')130 pPr = SubElement(p, 'a:pPr')131 SubElement(pPr, 'a:defRPr')132 r = SubElement(p, 'a:r')133 SubElement(r, 'a:rPr', {'lang':self.chart.lang})134 t = SubElement(r, 'a:t').text = axis.title135 SubElement(title, 'c:layout')136 SubElement(ax, 'c:tickLblPos', {'val':axis.tick_label_position})137 SubElement(ax, 'c:crossAx', {'val':str(axis.cross)})138 SubElement(ax, 'c:crosses', {'val':axis.crosses})139 if axis.auto:140 SubElement(ax, 'c:auto', {'val':'1'})141 if axis.label_align:142 SubElement(ax, 'c:lblAlgn', {'val':axis.label_align})143 if axis.label_offset:144 SubElement(ax, 'c:lblOffset', {'val':str(axis.label_offset)})145 if label == 'c:valAx':146 if self.chart.type == Chart.SCATTER_CHART:147 SubElement(ax, 'c:crossBetween', {'val':'midCat'})148 else:149 SubElement(ax, 'c:crossBetween', {'val':'between'})150 SubElement(ax, 'c:majorUnit', {'val':str(axis.unit)})151152 def _write_series(self, subchart):153154 for i, serie in enumerate(self.chart._series):155 ser = SubElement(subchart, 'c:ser')156 SubElement(ser, 'c:idx', {'val':str(i)})157 SubElement(ser, 'c:order', {'val':str(i)})158159 if serie.legend:160 tx = SubElement(ser, 'c:tx')161 self._write_serial(tx, serie.legend)162163 if serie.color:164 sppr = SubElement(ser, 'c:spPr')165 if self.chart.type == Chart.BAR_CHART:166 # fill color167 fillc = SubElement(sppr, 'a:solidFill')168 SubElement(fillc, 'a:srgbClr', {'val':serie.color})169 # edge color170 ln = SubElement(sppr, 'a:ln')171 fill = SubElement(ln, 'a:solidFill')172 SubElement(fill, 'a:srgbClr', {'val':serie.color})173174 if serie.error_bar:175 self._write_error_bar(ser, serie)176177 marker = SubElement(ser, 'c:marker')178 SubElement(marker, 'c:symbol', {'val':serie.marker})179180 if serie.labels:181 cat = SubElement(ser, 'c:cat')182 self._write_serial(cat, serie.labels)183184 if self.chart.type == Chart.SCATTER_CHART:185 if serie.xvalues:186 xval = SubElement(ser, 'c:xVal')187 self._write_serial(xval, serie.xvalues)188189 yval = SubElement(ser, 'c:yVal')190 self._write_serial(yval, serie.values)191 else:192 val = SubElement(ser, 'c:val')193 self._write_serial(val, serie.values)194195 def _write_serial(self, node, serie, literal=False):196197 cache = serie._get_cache()198 if isinstance(cache[0], basestring):199 typ = 'str'200 else:201 typ = 'num'202203 if not literal:204 if typ == 'num':205 ref = SubElement(node, 'c:numRef')206 else:207 ref = SubElement(node, 'c:strRef')208 SubElement(ref, 'c:f').text = serie._get_ref()209 if typ == 'num':210 data = SubElement(ref, 'c:numCache')211 else:212 data = SubElement(ref, 'c:strCache')213 else:214 data = SubElement(node, 'c:numLit')215216 if typ == 'num':217 SubElement(data, 'c:formatCode').text = 'General'218 if literal:219 values = (1,)220 else:221 values = cache222223 SubElement(data, 'c:ptCount', {'val':str(len(values))})224 for j, val in enumerate(values):225 point = SubElement(data, 'c:pt', {'idx':str(j)})226 SubElement(point, 'c:v').text = str(val)227228 def _write_error_bar(self, node, serie):229230 flag = {ErrorBar.PLUS_MINUS:'both',231 ErrorBar.PLUS:'plus',232 ErrorBar.MINUS:'minus'}233234 eb = SubElement(node, 'c:errBars')235 SubElement(eb, 'c:errBarType', {'val':flag[serie.error_bar.type]})236 SubElement(eb, 'c:errValType', {'val':'cust'})237238 plus = SubElement(eb, 'c:plus')239 self._write_serial(plus, serie.error_bar.values,240 literal=(serie.error_bar.type == ErrorBar.MINUS))241242 minus = SubElement(eb, 'c:minus')243 self._write_serial(minus, serie.error_bar.values,244 literal=(serie.error_bar.type == ErrorBar.PLUS))245246 def _write_legend(self, chart):247 248 if self.chart.show_legend:249 legend = SubElement(chart, 'c:legend')250 SubElement(legend, 'c:legendPos', {'val':self.chart.legend.position})251 SubElement(legend, 'c:layout')252253 def _write_print_settings(self, root):254255 settings = SubElement(root, 'c:printSettings')256 SubElement(settings, 'c:headerFooter')257 margins = dict([(k, str(v)) for (k, v) in self.chart.print_margins.iteritems()])258 SubElement(settings, 'c:pageMargins', margins)259 SubElement(settings, 'c:pageSetup')260261 def _write_shapes(self, root):262263 if self.chart._shapes:264 SubElement(root, 'c:userShapes', {'r:id':'rId1'})265266 def write_rels(self, drawing_id):267268 root = Element('Relationships', {'xmlns' : 'http://schemas.openxmlformats.org/package/2006/relationships'})269 attrs = {'Id' : 'rId1',270 'Type' : 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chartUserShapes',271 'Target' : '../drawings/drawing%s.xml' % drawing_id }272 SubElement(root, 'Relationship', attrs) ...

Full Screen

Full Screen

core.py

Source:core.py Github

copy

Full Screen

...130 start = stream.tell()131 elements = []132 while size is None or stream.tell() - start < size:133 try:134 element = parse_element(stream, specs)135 if element is None:136 continue137 logger.debug('%s %s parsed', element.__class__.__name__, element.name)138 if element.type in ignore_element_types or element.name in ignore_element_names:139 logger.info('%s %s ignored', element.__class__.__name__, element.name)140 if element.type == MASTER:141 stream.seek(element.size, 1)142 continue143 if element.type == MASTER:144 if max_level is not None and element.level >= max_level:145 logger.info('Maximum level %d reached for children of %s %s', max_level, element.__class__.__name__, element.name)146 stream.seek(element.size, 1)147 else:148 logger.debug('Loading child elements for %s %s with size %d', element.__class__.__name__, element.name, element.size)149 element.data = parse(stream, specs, element.size, ignore_element_types, ignore_element_names, max_level)150 elements.append(element)151 except ReadError:152 if size is not None:153 raise154 break155 return elements156def parse_element(stream, specs, load_children=False, ignore_element_types=None, ignore_element_names=None, max_level=None):157 """Extract a single :class:`Element` from the `stream` according to the `specs`158 :param stream: file-like object from which to read159 :param dict specs: see :ref:`specs`160 :param bool load_children: load children elements if the parsed element is a :class:`MasterElement`161 :param list ignore_element_types: list of element types to ignore162 :param list ignore_element_names: list of element names to ignore163 :param int max_level: maximum level for children elements164 :return: the parsed element165 :rtype: :class:`Element`166 """167 ignore_element_types = ignore_element_types if ignore_element_types is not None else []168 ignore_element_names = ignore_element_names if ignore_element_names is not None else []169 element_id = read_element_id(stream)170 if element_id is None:...

Full Screen

Full Screen

test_parsers.py

Source:test_parsers.py Github

copy

Full Screen

...22 self.validation = yaml.safe_load(yml)23 self.specs = ebml.get_matroska_specs()24 def tearDown(self):25 self.stream.close()26 def check_element(self, element_id, element_type, element_name, element_level, element_position, element_size, element_data, element,27 ignore_element_types=None, ignore_element_names=None, max_level=None):28 """Recursively check an element"""29 # base30 self.assertTrue(element.id == element_id)31 self.assertTrue(element.type == element_type)32 self.assertTrue(element.name == element_name)33 self.assertTrue(element.level == element_level)34 self.assertTrue(element.position == element_position)35 self.assertTrue(element.size == element_size)36 # Element37 if not isinstance(element_data, list):38 self.assertTrue(type(element) == ebml.Element)39 if element_type != ebml.BINARY:40 self.assertTrue(element.data == element_data)41 return42 # MasterElement43 if ignore_element_types is not None: # filter validation on element types44 element_data = [e for e in element_data if e[1] not in ignore_element_types]45 if ignore_element_names is not None: # filter validation on element names46 element_data = [e for e in element_data if e[2] not in ignore_element_names]47 if element.level == max_level: # special check when maximum level is reached48 self.assertTrue(element.data is None)49 return50 self.assertTrue(len(element.data) == len(element_data))51 for i in range(len(element.data)):52 self.check_element(element_data[i][0], element_data[i][1], element_data[i][2], element_data[i][3],53 element_data[i][4], element_data[i][5], element_data[i][6], element.data[i], ignore_element_types,54 ignore_element_names, max_level)55 def test_parse_full(self):56 result = ebml.parse(self.stream, self.specs)57 self.assertTrue(len(result) == len(self.validation))58 for i in range(len(self.validation)):59 self.check_element(self.validation[i][0], self.validation[i][1], self.validation[i][2], self.validation[i][3],60 self.validation[i][4], self.validation[i][5], self.validation[i][6], result[i])61 def test_parse_ignore_element_types(self):62 ignore_element_types = [ebml.INTEGER, ebml.BINARY]63 result = ebml.parse(self.stream, self.specs, ignore_element_types=ignore_element_types)64 self.validation = [e for e in self.validation if e[1] not in ignore_element_types]65 self.assertTrue(len(result) == len(self.validation))66 for i in range(len(self.validation)):67 self.check_element(self.validation[i][0], self.validation[i][1], self.validation[i][2], self.validation[i][3],68 self.validation[i][4], self.validation[i][5], self.validation[i][6], result[i], ignore_element_types=ignore_element_types)69 def test_parse_ignore_element_names(self):70 ignore_element_names = ['EBML', 'SimpleBlock']71 result = ebml.parse(self.stream, self.specs, ignore_element_names=ignore_element_names)72 self.validation = [e for e in self.validation if e[2] not in ignore_element_names]73 self.assertTrue(len(result) == len(self.validation))74 for i in range(len(self.validation)):75 self.check_element(self.validation[i][0], self.validation[i][1], self.validation[i][2], self.validation[i][3],76 self.validation[i][4], self.validation[i][5], self.validation[i][6], result[i], ignore_element_names=ignore_element_names)77 def test_parse_max_level(self):78 max_level = 379 result = ebml.parse(self.stream, self.specs, max_level=max_level)80 self.validation = [e for e in self.validation if e[3] <= max_level]81 self.assertTrue(len(result) == len(self.validation))82 for i in range(len(self.validation)):83 self.check_element(self.validation[i][0], self.validation[i][1], self.validation[i][2], self.validation[i][3],84 self.validation[i][4], self.validation[i][5], self.validation[i][6], result[i], max_level=max_level)85def generate_yml(filename, specs):86 """Generate a validation file for the test video"""87 def _to_builtin(elements):88 """Recursively convert elements to built-in types"""89 result = []90 for e in elements:91 if isinstance(e, ebml.MasterElement):92 result.append((e.id, e.type, e.name, e.level, e.position, e.size, _to_builtin(e.data)))93 else:94 result.append((e.id, e.type, e.name, e.level, e.position, e.size, None if isinstance(e.data, io.BytesIO) else e.data))95 return result96 video = io.open(os.path.join(TEST_DIR, filename), 'rb')97 yml = io.open(os.path.join(EBML_VALIDATION_DIR, filename + '.yml'), 'w')...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1root.element("elementName");2root.element("elementName").element("elementName");3root.element("elementName").element("elementName").element("elementName");4root.element("elementName").element("elementName").element("elementName").element("elementName");5root.element("elementName").element("elementName").element("elementName").element("elementName").element("elementName");6root.element("elementName").element("elementName").element("elementName").element("elementName").element("elementName").element("elementName");7root.element("elementName").element("elementName").element("elementName").element("elementName").element("elementName").element("elementName").element("elementName");

Full Screen

Using AI Code Generation

copy

Full Screen

1root.element('elementName', function(err, elem) {2});3elem.element('elementName', function(err, elem) {4});5root.element('elementName', function(err, elem) {6 elem.element('elementName2', function(err, elem) {7 });8});9root.element('elementName', function(err, elem) {10 elem.element('elementName2', function(err, elem) {11 elem.element('elementName3', function(err, elem) {12 });13 });14});15root.element('elementName', function(err, elem) {16 elem.element('elementName2', function(err, elem) {17 elem.element('elementName3', function(err, elem) {18 elem.element('elementName4', function(err, elem) {19 });20 });21 });22});

Full Screen

Using AI Code Generation

copy

Full Screen

1var root = document.documentElement;2var rootStyle = root.currentStyle || window.getComputedStyle(root);3var rootFontSize = parseFloat(rootStyle.fontSize);4var element = document.getElementById('element');5var elementStyle = element.currentStyle || window.getComputedStyle(element);6var elementFontSize = parseFloat(elementStyle.fontSize);7var elementWidth = element.offsetWidth;8var elementHeight = element.offsetHeight;9var elementWidthInEm = elementWidth / rootFontSize;10var elementHeightInEm = elementHeight / rootFontSize;11var root = document.documentElement;12var rootStyle = root.currentStyle || window.getComputedStyle(root);13var rootFontSize = parseFloat(rootStyle.fontSize);14var element = document.getElementById('element');15var elementStyle = element.currentStyle || window.getComputedStyle(element);16var elementFontSize = parseFloat(elementStyle.fontSize);17var elementWidth = element.offsetWidth;18var elementHeight = element.offsetHeight;19var elementWidthInEm = elementWidth / elementFontSize;20var elementHeightInEm = elementHeight / elementFontSize;21var root = document.documentElement;22var rootStyle = root.currentStyle || window.getComputedStyle(root);23var rootFontSize = parseFloat(rootStyle.fontSize);24var element = document.getElementById('element');25var elementStyle = element.currentStyle || window.getComputedStyle(element);26var elementFontSize = parseFloat(elementStyle.fontSize);27var elementWidth = element.offsetWidth;28var elementHeight = element.offsetHeight;29var elementWidthInEm = elementWidth / elementFontSize;

Full Screen

Using AI Code Generation

copy

Full Screen

1var el = document.getElementById('header');2el.textContent = 'New Header';3var el = document.getElementById('header');4el.textContent = 'New Header';5var el = document.getElementById('header');6el.textContent = 'New Header';7var el = document.getElementById('header');8el.textContent = 'New Header';9var el = document.getElementById('header');10el.textContent = 'New Header';11var el = document.getElementById('header');12el.textContent = 'New Header';13var el = document.getElementById('header');14el.textContent = 'New Header';15var el = document.getElementById('header');16el.textContent = 'New Header';17var el = document.getElementById('header');18el.textContent = 'New Header';19var el = document.getElementById('header');20el.textContent = 'New Header';21var el = document.getElementById('header');22el.textContent = 'New Header';23var el = document.getElementById('header');24el.textContent = 'New Header';

Full Screen

Using AI Code Generation

copy

Full Screen

1var rootElement = root.element;2var rootElement = root.element;3var rootElement = root.element;4var rootElement = root.element;5var rootElement = root.element;6var rootElement = root.element;7var rootElement = root.element;8var rootElement = root.element;9var rootElement = root.element;10var rootElement = root.element;11var rootElement = root.element;12var rootElement = root.element;13var rootElement = root.element;14var rootElement = root.element;15var rootElement = root.element;16var rootElement = root.element;17var rootElement = root.element;

Full Screen

Using AI Code Generation

copy

Full Screen

1The example below shows the usage of the element() method:2The example below shows the usage of the element() method:3The example below shows the usage of the element() method:4The example below shows the usage of the element() method:5The example below shows the usage of the element() method:6The example below shows the usage of the element() method:7The example below shows the usage of the element() method:8The element() method is used to select the element of the root. The element method is used to select the element of the root. The path of the element is passed as

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful