def test_three_phase_capacitor_writing(): m = Store() # Create a three phase, 900kVar capacitor cap1 = Capacitor(m) cap1.connecting_element = "bus66" cap1.nominal_voltage = 4.16 * 10**3 cap1.name = "cap1" for phase in ["A", "B", "C"]: cap1.phase_capacitors.append( PhaseCapacitor(m, phase=phase, var=300 * 10**3)) output_path = tempfile.gettempdir() w = Writer(output_path=output_path) w.write(m) # Check that the OpenDSS writer created a Master file assert os.path.exists(os.path.join(output_path, "Master.dss")) # Check that the OpenDSS writer created a Capacitors.dss file assert os.path.exists(os.path.join(output_path, "Capacitors.dss")) with open(os.path.join(output_path, "Capacitors.dss"), "r") as fp: lines = fp.readlines() assert (len(lines) == 2 ) # There is one line with the capacitor string and one empty line assert lines[ 0] == "New Capacitor.cap1 Bus1=bus66 phases=3 Kv=4.16 Kvar=900.0\n"
def create_output_dir(tests_dir): """Reading the input from every reader for each test case and creating the Opendss output.""" # Creating output directory current_dir = os.path.realpath(os.path.dirname(__file__)) validation_dir = os.path.join(current_dir, "validation_outputs") if os.path.exists(validation_dir): shutil.rmtree(validation_dir) for each in os.listdir(tests_dir): if each == "cim" or each == "demo": continue for dirname in os.listdir(os.path.join(tests_dir, each)): if dirname == "storage_test": continue output_dir = os.path.join(validation_dir, dirname, each + "_output") test_path = os.path.join(tests_dir, each, dirname) m = Store() if each == "opendss": r1 = OpenDSS_Reader( master_file=os.path.join(test_path, "master.dss")) elif each == "synergi": if dirname == "ieee_4node": r1 = Synergi_Reader( input_file=os.path.join(test_path, "network.mdb")) elif each == "cyme": r1 = Cyme_Reader(data_folder_path=os.path.join(test_path)) elif each == "gridlabd": r1 = Gridlabd_Reader( input_file=os.path.join(test_path, "node.glm")) r1.parse(m) w1 = OpenDSS_Writer(output_path=output_dir) w1.write(m, separate_feeders=True) return validation_dir
def test_lines_write(): m = Store() r = Reader( master_file=os.path.join( current_directory, "../../../readers/opendss/Lines/test_linegeometries.dss" ) ) r.parse(m) m.set_names() output_path = tempfile.gettempdir() jw = Json_Writer(output_path=output_path) jw.write(m) w = Writer(output_path=output_path) w.write(m) # Check that the OpenDSS writer created a Master file assert os.path.exists(os.path.join(output_path, "Master.dss")) r_w = Reader(master_file=os.path.join(output_path, "Master.dss")) r_w.parse(m) m.set_names() jw = Json_Writer(output_path="./") jw.write(m) with open(os.path.join(output_path, "Model.json"), "r") as f1: reader_json = json.load(f1) with open("./Model.json", "r") as f2: writer_json = json.load(f2) assert reader_json["model"] == writer_json["model"]
def test_cyme_to_opendss(): ''' Test the Cyme to OpenDSS conversion. ''' list_of_directories = [] from ditto.store import Store from ditto.readers.cyme.read import Reader from ditto.writers.opendss.write import Writer import opendssdirect as dss cyme_models = [ f for f in os.listdir( os.path.join(current_directory, 'data/small_cases/cyme/')) if not f.startswith('.') ] for model in cyme_models: print(model) m = Store() r = Reader(data_folder_path=os.path.join( current_directory, 'data/small_cases/cyme', model)) r.parse(m) #TODO: Log properly # print('>Cyme model {model} read...'.format(model=model)) output_path = tempfile.TemporaryDirectory() list_of_directories.append(output_path) w = Writer(output_path=output_path.name) w.write(m) #TODO: Log properly # print('>...and written to OpenDSS.\n') print(model) dss.run_command("clear")
def test_single_phase_capacitor_writing(): m = Store() # Create a one phase, 100kVar capacitor on phase A cap1 = Capacitor(m) cap1.name = "cap1" cap1.nominal_voltage = 4.16 * 10**3 cap1.connecting_element = "bus23" cap1_A = PhaseCapacitor(m) cap1_A.phase = "A" cap1_A.var = 100 * 10**3 cap1.phase_capacitors.append(cap1_A) output_path = tempfile.gettempdir() w = Writer(output_path=output_path) w.write(m) # Check that the OpenDSS writer created a Master file assert os.path.exists(os.path.join(output_path, "Master.dss")) # Check that the OpenDSS writer created a Capacitors.dss file assert os.path.exists(os.path.join(output_path, "Capacitors.dss")) with open(os.path.join(output_path, "Capacitors.dss"), "r") as fp: lines = fp.readlines() assert (len(lines) == 2 ) # There is one line with the capacitor string and one empty line assert lines[ 0] == "New Capacitor.cap1 Bus1=bus23.1 phases=1 Kv=4.16 Kvar=100.0\n"
def test_write_linecodes(): """Test the write_linecodes() method.""" from ditto.writers.opendss.write import Writer line = setup_line_test() output_path = tempfile.gettempdir() w = Writer(output_path=output_path) w.write_linecodes([line])
def test_write_wiredata(): """Test the method write_wiredata().""" from ditto.writers.opendss.write import Writer line = setup_line_test() output_path = tempfile.gettempdir() w = Writer(output_path=output_path) w.write_wiredata([line])
def apply(cls, stack, output_path, base_dir, separate_feeders, separate_substations): if base_dir and (not os.path.exists(output_path)): output_path = os.path.join(base_dir, output_path) writer = Writer(linecodes_flag=True, output_path=output_path) logger.debug("Writing {!r} out to {!r}.".format( stack.model, output_path)) writer.write(stack.model, verbose=False, separate_feeders=separate_feeders, separate_substations=separate_substations ) #i.e. break opendss network into subregions return True
def test_opendss_transformer(): opendss_test_data = """ Clear new circuit.IEEE13 ~ basekv=4.16 pu=1.0000 phases=3 bus1=SourceBus ~ Angle=0 ~ MVAsc3=200000 MVASC1=200000 ! stiffen the source to approximate inf source New Transformer.reg Phases=3 Windings=2 XHL=0.01 ~ wdg=1 bus=Sourcebus.1.2.3.0 conn=Wye kv=4.16 kva=5000 %r=0.000498 XHT=.00498 ~ wdg=2 bus=651.1.2.3 conn=Wye kv=4.16 kva=5000 %r=0.000498 XLT=.00498 New Transformer.XFM1 Phases=3 Windings=2 XHL=2 ~ wdg=1 bus=633.1.2.3.0 conn=Wye kv=4.16 kva=500 %r=.55 XHT=1 ~ wdg=2 bus=634.1.2.3 conn=Wye kv=0.480 kva=500 %r=.55 XLT=1 """ master_file = os.path.join(tempfile.gettempdir(), os.urandom(24).hex()) # TODO: figure out why named temporary file doesn't work as expected on windows # master_file = tempfile.NamedTemporaryFile(mode="w") with open(master_file, "w") as f: f.write(opendss_test_data) m = Store() r = Reader(master_file=master_file, ) r.parse(m) m.set_names() for t in m.iter_models(type=PowerTransformer): assert len(t.windings) == 2 assert t.windings[0].is_grounded is True assert t.windings[1].is_grounded is False output_path = tempfile.TemporaryDirectory() w = Writer(output_path=output_path.name) w.write(m) with open(os.path.join(output_path.name, "Transformers.dss")) as f: string = f.read() assert "sourcebus.1.2.3.0" in string assert "651.1.2.3.0" not in string assert "651.1.2.3" in string assert "633.1.2.3.0" in string assert "634.1.2.3.0" not in string assert "634.1.2.3" in string
def test_opendss_center_transformer(): opendss_test_data = """ Clear new circuit.IEEE13 ~ basekv=4.16 pu=1.0000 phases=3 bus1=SourceBus ~ Angle=0 ~ MVAsc3=200000 MVASC1=200000 ! stiffen the source to approximate inf source New Transformer.Example1-ph phases=1 Windings=3 ~ Xhl=2.04 Xht=2.04 Xlt=1.36 %noloadloss=.2 ~ Buses=[bus1.1.2 bus2.1.0 bus2.0.2] ! mid-point of secondary is grounded ~ kVs=[12.47 .12 .12] ! ratings of windings ~ kVAs=[25 25 25] ~ %Rs = [0.6 1.2 1.2] ~ conns=[delta wye wye] """ master_file = os.path.join(tempfile.gettempdir(), os.urandom(24).hex()) # TODO: figure out why named temporary file doesn't work as expected on windows # master_file = tempfile.NamedTemporaryFile(mode="w") with open(master_file, "w") as f: f.write(opendss_test_data) m = Store() r = Reader(master_file=master_file) r.parse(m) m.set_names() for t in m.iter_models(type=PowerTransformer): assert len(t.windings) == 3 assert t.windings[0].is_grounded is False assert t.windings[1].is_grounded is False assert t.windings[2].is_grounded is False output_path = tempfile.TemporaryDirectory() w = Writer(output_path=output_path.name) w.write(m) with open(os.path.join(output_path.name, "Transformers.dss")) as f: string = f.read() assert "bus1.1.2 " in string assert "bus2.1.0 " in string assert "bus2.0.2 " in string
def test_parse_concentric_neutral_cable(): """ Tests the parsing of concentric neutral cables. The example used is: New CNDATA.250_1/3 k=13 DiaStrand=0.064 Rstrand=2.816666667 epsR=2.3 ~ InsLayer=0.220 DiaIns=1.06 DiaCable=1.16 Rac=0.076705 GMRac=0.20568 diam=0.573 ~ Runits=kft Radunits=in GMRunits=in """ from ditto.store import Store from ditto.models.wire import Wire from ditto.writers.opendss.write import Writer m = Store() wire = Wire( m, phase="A", nameclass="250_1/3", diameter=0.0145542, # 0.573 inches in meters gmr=0.005224272, # 0.20568 inches in meters ampacity=500, emergency_ampacity=1000, resistance=0.000251656824147, # 0.076705 ohm/kft in ohm/meter concentric_neutral_resistance= 0.00924103237205, # 2.816666667 ohm/kft in ohm/meter concentric_neutral_diameter=0.0016256, # 0.064 inches in meters concentric_neutral_outside_diameter=0.029464, # 1.16 inches in meters concentric_neutral_nstrand=13, ) output_path = tempfile.gettempdir() w = Writer(output_path=output_path) parsed_cable = w.parse_cable(wire) assert parsed_cable["k"] == 13 assert parsed_cable["DiaStrand"] == 0.0016256 assert parsed_cable["Rstrand"] == 0.00924103237205 assert parsed_cable["Diam"] == 0.0145542 assert parsed_cable["DiaCable"] == 0.029464 assert parsed_cable["Rac"] == 0.000251656824147 assert parsed_cable["GMRac"] == 0.005224272 assert parsed_cable["Runits"] == "m" assert parsed_cable["Radunits"] == "m" assert parsed_cable["GMRunits"] == "m"
def main(): ''' Conversion example of the IEEE 123 node system. CYME ---> OpenDSS example. This example uses the glm file located in tests/data/big_cases/cyme/ieee_123node ''' #Path settings (assuming it is run from examples folder) #Change this if you wish to use another system path = '../tests/data/big_cases/cyme/ieee_123node' ############################ # STEP 1: READ FROM CYME # ############################ # #Create a Store object print('>>> Creating empty model...') model = Store() #Instanciate a Reader object r = Reader(data_folder_path=path) #Parse (can take some time for large systems...) print('>>> Reading from CYME...') start = time.time() #basic timer r.parse(model) end = time.time() print('...Done (in {} seconds'.format(end - start)) ############################## # STEP 2: WRITE TO OpenDSS # ############################## # #Instanciate a Writer object w = Writer(output_path='./') #Write to OpenDSS (can also take some time for large systems...) print('>>> Writing to OpenDSS...') start = time.time() #basic timer w.write(model) end = time.time() print('...Done (in {} seconds'.format(end - start))
def test_write_linegeometry(): """Test the write_linegeometry() method.""" from ditto.writers.opendss.write import Writer line = setup_line_test() output_path = tempfile.gettempdir() w = Writer(output_path=output_path) w.write_wiredata([line]) w.write_linegeometry([line]) with open(os.path.join(output_path, "LineGeometry.dss"), "r") as fp: lines = fp.readlines() assert get_property_from_dss_string(lines[0], "reduce") == "y" assert get_property_from_dss_string(lines[0], "nconds") == "4" assert get_property_from_dss_string(lines[0], "nphases") == "3" assert get_property_from_dss_string(lines[0], "units") == "m" assert get_property_from_dss_string(lines[0], "normamps") == [ "500.0", "500.0", "500.0", "500.0", ] assert get_property_from_dss_string(lines[0], "Emergamps") == [ "1000.0", "1000.0", "1000.0", "1000.0", ]
def test_parse_wire(): from ditto.store import Store from ditto.models.wire import Wire from ditto.writers.opendss.write import Writer m = Store() wire_A = Wire( m, phase="A", nameclass="wire_test_phase", diameter=5, gmr=10, ampacity=500, emergency_ampacity=1000, resistance=5, ) output_path = tempfile.gettempdir() w = Writer(output_path=output_path) parsed_wire = w.parse_wire(wire_A) assert parsed_wire["GMRac"] == 10 assert parsed_wire["Diam"] == 5 assert parsed_wire["normamps"] == 500 assert parsed_wire["emergamps"] == 1000 assert parsed_wire["Rac"] == 5
from ditto.readers.windmil_ascii.read import Reader from ditto.writers.opendss.write import Writer from ditto.store import Store m = Store() Path = {'network_folder': r'C:\Users\alatif\Desktop\Test-Exports\ASCII\Basalt'} windmil_reader = Reader(**Path) windmil_reader.parse(m) OpenDSS_writer = Writer( output_path=r'C:\Users\alatif\Desktop\Test-Exports\OpenDSS\Basalt') OpenDSS_writer.write(m)
from ditto.readers.windmil.read import Reader from ditto.writers.opendss.write import Writer from ditto.store import Store m = Store() windmil_reader = Reader() windmil_reader.parse(m) OpenDSS_writer = Writer() OpenDSS_writer.write(m)
def run(self): # relative import (relative to THIS MODULE) if os.path.isabs(self.ditto_folder): # keep it df = self.ditto_folder else: df = os.path.join(os.path.dirname(os.path.realpath(__file__)), self.ditto_folder) sys.path.insert( 0, df ) # don't append in case there are other multiple DiTTo installations. from ditto.store import Store from ditto.writers.opendss.write import Writer from reader.read import Reader model = Store() reader = Reader(geojson_file=self.geojson_file, equipment_file=self.equipment_file, load_folder=self.urbanopt_scenario, use_reopt=self.use_reopt, is_timeseries=True, timeseries_location=self.timeseries_location, relative_timeseries_location=os.path.join( '..', 'profiles')) reader.parse(model) if not os.path.exists(os.path.join(self.dss_analysis, 'dss_files')): os.makedirs(os.path.join(self.dss_analysis, 'dss_files'), exist_ok=True) if not os.path.exists( os.path.join(self.dss_analysis, 'results', 'Features')): os.makedirs(os.path.join(self.dss_analysis, 'results', 'Features'), exist_ok=True) if not os.path.exists( os.path.join(self.dss_analysis, 'results', 'Transformers')): os.makedirs(os.path.join(self.dss_analysis, 'results', 'Transformers'), exist_ok=True) if not os.path.exists( os.path.join(self.dss_analysis, 'results', 'Lines')): os.makedirs(os.path.join(self.dss_analysis, 'results', 'Lines'), exist_ok=True) writer = Writer(output_path=os.path.join(self.dss_analysis, 'dss_files'), split_feeders=False, split_substations=False) writer.write(model) ts = pd.read_csv(os.path.join(self.timeseries_location, 'timestamps.csv'), header=0) number_iterations = len(ts) voltage_df_dic = {} line_df_dic = {} transformer_df_dic = {} delta = datetime.datetime.strptime( ts.loc[1]['Datetime'], '%Y/%m/%d %H:%M:%S') - datetime.datetime.strptime( ts.loc[0]['Datetime'], '%Y/%m/%d %H:%M:%S') interval = delta.seconds / 3600.0 stepsize = 60 * interval building_map = {} geojson_content = [] try: with open(self.geojson_file, 'r') as f: geojson_content = json.load(f) except: raise IOError("Problem trying to read json from file " + self.geojson_file) for element in geojson_content["features"]: if 'properties' in element and 'type' in element[ 'properties'] and 'buildingId' in element[ 'properties'] and element['properties'][ 'type'] == 'ElectricalJunction': building_map[element['properties'] ['id']] = element['properties']['buildingId'] for i, row in ts.iterrows(): time = row['Datetime'] print(i, flush=True) hour = int(i / (1 / interval)) seconds = (i % (1 / interval)) * 3600 location = os.path.join(self.dss_analysis, 'dss_files', 'Master.dss') dss.run_command("Clear") dss.run_command("Redirect " + location) dss.run_command("Solve mode=yearly stepsize=" + str(stepsize) + "m number=1 hour=" + str(hour) + " sec=" + str(seconds)) voltages = self._get_all_voltages() line_overloads = self._get_line_loading() overloaded_xfmrs = self._get_xfmr_overloads() for element in voltages: if element not in building_map: continue building_id = building_map[element] if building_id not in voltage_df_dic: voltage_df_dic[building_id] = pd.DataFrame(columns=[ 'Datetime', 'p.u. voltage', 'overvoltage', 'undervoltage' ]) voltage_df_dic[building_id].loc[i] = [ time, voltages[element], voltages[element] > 1.05, voltages[element] < 0.95 ] for element in line_overloads: if element not in line_df_dic: line_df_dic[element] = pd.DataFrame( columns=['Datetime', 'p.u. loading', 'overloaded']) line_df_dic[element].loc[i] = [ time, line_overloads[element], line_overloads[element] > 1.0 ] for element in overloaded_xfmrs: if element not in transformer_df_dic: transformer_df_dic[element] = pd.DataFrame( columns=['Datetime', 'p.u. loading', 'overloaded']) transformer_df_dic[element].loc[i] = [ time, overloaded_xfmrs[element], overloaded_xfmrs[element] > 1.0 ] for element in voltage_df_dic: voltage_df_dic[element].to_csv(os.path.join( self.dss_analysis, 'results', 'Features', element + '.csv'), header=True, index=False) for element in line_df_dic: line_df_dic[element].to_csv(os.path.join(self.dss_analysis, 'results', 'Lines', element + '.csv'), header=True, index=False) for element in transformer_df_dic: transformer_df_dic[element].to_csv(os.path.join( self.dss_analysis, 'results', 'Transformers', element + '.csv'), header=True, index=False)