Ejemplo n.º 1
0
def build_settings(snapshots: List[Dict] = [], playerSettings: Dict[str, Any] = {}) -> Dict[str, Any]:
    # load template - settings.yaml
    settings = load_templates("settings")

    # inject the snapshots
    if len(snapshots) > 0:
        print(f"\t- {len(snapshots)} snapshot found. adding to map.")
        settings = merge(settings, {"snapshots": snapshots})
    else:
        # if no snapshot defined load the default template and fix the size by and color by
        print(f"\t- no snapshot found. injecting default")
        default_snap = load_templates("snapshot")
        default_snap = merge(
            default_snap,
            {
                "layout": {
                    "plotType": "network",
                    "settings": {"nodeSizeStrat": "fixed", "nodeColorStrat": "fixed"},
                }
            },
        )
        settings = merge(settings, {"snapshots": [default_snap]})

    settings = merge(settings, {"player": {"settings": playerSettings}})

    return settings
Ejemplo n.º 2
0
 def loadTemplates(self, game_dir):
     self.templates, self.template_affordances = utils.load_templates(
         game_dir)
     print('Tiles and affordances loaded')
     self.sprites, self.sprite_affordances = utils.load_sprites_and_masks(
         game_dir)
     print('Sprites, masks, and affordances loaded')
Ejemplo n.º 3
0
def build_attrDescriptors(
        datapointAttrPath: Union[Path, str]) -> List[Dict[str, Any]]:

    df_attrs: pd.DataFrame = pd.read_csv(str(datapointAttrPath))
    attrDescriptorTpl = load_templates("datapointAttribs")

    df_attrs.fillna(value="", inplace=True)
    attrDescriptors = []
    for _, row in df_attrs.iterrows():
        # extract the attr (each row) data as a dict
        attrs: Dict[str, Any] = dict(row)

        # metadata
        # meta_attrs = dict((k, attrs[k]) for k in attrDescriptorTpl["metadata"])
        # other_attrs = dict((k, attrs[k]) for k in attrs if k not in meta_attrs)
        # attrs = {**other_attrs, **{"metadata": meta_attrs}}
        meta_tpl = attrDescriptorTpl["metadata"]
        meta_attrs = dict((k, attrs[k]) for k in meta_tpl if k in attrs)
        other_attrs = dict((k, attrs[k]) for k in attrs if k not in meta_attrs)
        attrs = {**other_attrs, **{"metadata": {**meta_tpl, **meta_attrs}}}

        # if title doesnt exist. copy from id.
        attrs[
            "title"] = attrs["id"] if attrs["title"] == "" else attrs["title"]
        # merge with template to form the full descriptor
        at = {**attrDescriptorTpl, **attrs}

        # collect attr descriptor
        attrDescriptors.append(at)

    return attrDescriptors
Ejemplo n.º 4
0
def build_datapoints(dpPath: str, dpAttribTypes) -> List[Dict[str, Any]]:
    df_datapoints: pd.DataFrame = pd.read_csv(dpPath)

    # load datapoint template - datapoint.yaml
    datapointTpl = load_templates("datapoint")

    datapoints = []
    for _, dp in df_datapoints.iterrows():
        # structure the datapoint (each row) as a dict
        attrs: Dict[str, Any] = dict(dp)

        # validate the attr vals based on type.
        for key, val in attrs.items():
            if dpAttribTypes[key] == "liststring":
                # check if value is NaN or not string type
                if isinstance(val, str):
                    # convert any liststring attr into a list
                    attrs[key] = val.split("|") if "|" in val else [val]
                else:
                    attrs[key] = ""
            elif dpAttribTypes[key] == "float" or dpAttribTypes[
                    key] == "integer" or dpAttribTypes[key] == "year":
                attrs[key] = val if not pd.isna(attrs[key]) else ""
            else:
                attrs[key] = val if not pd.isna(attrs[key]) else ""

        # merge attrs with template
        dp = {**datapointTpl, **{"id": f'{dp["id"]}', "attr": attrs}}

        # collect datapoint
        datapoints.append(dp)

    return datapoints
Ejemplo n.º 5
0
def __write_dataset_file(datapointsPath: Union[Path, str],
                         datapointAttrPath: Union[Path,
                                                  str], out_data_dir: Path):
    # collect datapoint attributes
    datapointAttribs = build_attrDescriptors(str(datapointAttrPath))
    datapointAttrTypes = {
        row["id"]: row["attrType"]
        for row in datapointAttribs
    }
    # print(f"\t- processed {len(datapointAttribs)} datapoint attributes {[at['id'] for at in datapointAttribs]}")

    # collect datapoints
    datapoints = build_datapoints(str(datapointsPath), datapointAttrTypes)
    print(
        f"\t- processed {len(datapoints)} datapoints with {datapoints[0].keys()} where attr={list(datapoints[0]['attr'].keys())}"
    )

    # merge into dataset
    datasetTpl = load_templates("dataset")
    data = {
        **datasetTpl,
        **{
            "attrDescriptors": datapointAttribs,
            "datapoints": datapoints
        }
    }
    with open(out_data_dir / "nodes.json", mode="w") as f:
        json.dump(data, f, indent=4)
Ejemplo n.º 6
0
def create_snapshot(name: str,
                    subtitle: str,
                    summaryImg: str = "",
                    description: str = "",
                    layout_params: Dict = {}):
    """creates a snapshot object

    Args:
        name (str): snapshot title
        subtitle (str): snapshot subtitle
        summaryImg (str, optional): link to an image (ratio:110x80). Defaults to "".
        description (str, optional): description of snapshot. html ok.[description]. Defaults to "".
        layout_params (Dict, optional): see templates/snapshot.yaml. Defaults to {}.

    Returns:
        [Dict[str,Any]]: a snapshot object
    """
    snapTpl = load_templates("snapshot")

    # inject layout settings
    snapTpl["layout"] = merge(snapTpl["layout"], layout_params)

    # set name and subtitle
    snapTpl = merge(
        snapTpl,
        {
            "id": str(uuid.uuid4()),
            "snapName": name,
            "subtitle": subtitle,
            "summaryImg": summaryImg,
            "descr": description,
        },
    )

    return snapTpl
Ejemplo n.º 7
0
def __write_network_file(
    datapointsPath: Union[Path, str],
    linksPath: Union[Path, str],
    node_attr_map: Dict[str, str],
    link_attr_map: Dict[str, str],
    out_data_dir: Path,
):
    # collect nodes
    nodes = build_nodes(dpPath=datapointsPath, attr_map=node_attr_map)
    print(
        f"\t- processed {len(nodes)} nodes with {nodes[0].keys()} where attr={list(nodes[0]['attr'].keys())}"
    )

    # collect links
    links = build_links(linksPath=linksPath, attr_map=link_attr_map)
    print(
        f"\t- processed {len(links)} links with {links[0].keys()} where attr={list(links[0]['attr'].keys())}"
    )

    # collect node attributes
    nodeAttribs = build_nodeAttrDescriptors()
    print(
        f"\t- processed {len(nodeAttribs)} node attributes {[at['id'] for at in nodeAttribs]}"
    )

    # collect link attribs
    linkAttribs = build_linkAttrDescriptors()
    print(
        f"\t- processed {len(linkAttribs)} link attributes {[at['id'] for at in linkAttribs]}"
    )

    # write network file
    networkTpl = load_templates("network")
    data = {
        **networkTpl,
        **{
            "nodes": nodes,
            "links": links,
            "nodeAttrDescriptors": nodeAttribs,
            "linkAttrDescriptors": linkAttribs
        },
    }
    # pprint.pprint(data)

    with open(out_data_dir / "links.json", mode="w") as f:
        json.dump([data], f, indent=4)
Ejemplo n.º 8
0
    def create_case_from_wizard(self):
        default_dict = load_templates()
        objects = {}
        objects['Valves'] = []
        objects['Tubes'] = []
        objects['Atmospheres'] = []
        objects['Junctions'] = []
        objects['Cylinders'] = []
        objects['Tanks'] = []
        X_SIZE = 66
        Y_SIZE = 66

        ncyls = self.ui_ncd.ncyls.value()
        for icyl in range(0, ncyls):
            default_dict['Configurations']['ig_order'].append(icyl)
        # Cambiar los nombres de los folders segun el elegido por el usario
        default_dict['Configurations'][
            'folder_name'] = '%s_folder' % self.case_name
        default_dict['Configurations'][
            'filesave_state'] = '%s_state' % self.case_name
        default_dict['Configurations'][
            'filesave_spd'] = '%s_species' % self.case_name
        default_dict['Configurations']['nstroke'] = int(
            self.ui_ncd.nstroke.currentText())
        cw = configurationWidget(default_dict['Configurations'],
                                 self.case_name)

        INITIAL_Y = Y_SIZE * (ncyls - 1)

        # creacion de los objetos
        iobject = copy.deepcopy(default_dict['Atmospheres'])
        position = QtCore.QPoint(0, INITIAL_Y)
        item_atmosphere = SceneItem('Atmospheres', position, iobject)
        objects['Atmospheres'].append(item_atmosphere)

        iobject = copy.deepcopy(default_dict['Tubes'])
        iobject['tright'] = 'tank'
        iobject['tleft'] = 'atmosphere'
        iobject['nright'] = 0
        iobject['nleft'] = 0
        iobject['label'] = 'Tube_0'
        configure_default_tube(iobject)
        position = QtCore.QPoint(X_SIZE * 2, INITIAL_Y)
        item_tube = SceneItem('Tubes', position, iobject)
        objects['Tubes'].append(item_tube)

        iobject = copy.deepcopy(default_dict['Tanks'])
        iobject['int2tube'] = [0]
        iobject['nnod'] = ncyls + 2
        iobject['label'] = 'Tank_0'
        # un state_ini ya viene en el template, nnod: 1 + 1 tube + ncyls
        for isi in range(ncyls + 1):
            iobject['state_ini'].append(DEFAULT_DVP)
            iobject['Cd_ports'].append(0.8)
        position = QtCore.QPoint(X_SIZE * 3, INITIAL_Y)
        item_tank = SceneItem('Tanks', position, iobject)
        objects['Tanks'].append(item_tank)

        iobject = copy.deepcopy(default_dict['Junctions'])
        iobject['nnod'] = ncyls + 1
        iobject['label'] = 'Junction_0'
        # nnod: 1 tube + ncyls
        for isi in range(ncyls + 1):
            iobject['state_ini'].append(DEFAULT_DVP)
        position = QtCore.QPoint(X_SIZE * 13, INITIAL_Y)
        item_junc = SceneItem('Junctions', position, iobject)
        objects['Junctions'].append(item_junc)

        # TODO: controlar esto!!
        for icyl in range(0, ncyls):
            iobject = copy.deepcopy(default_dict['Valves'])
            iobject['ncyl'] = icyl
            iobject['typeVal'] = 'int'
            iobject['label'] = 'Intake_Valve_%s' % icyl
            configure_default_valve(iobject,
                                    default_dict['Configurations']['nstroke'])
            position = QtCore.QPoint(X_SIZE * 7, Y_SIZE * icyl * 2)
            item_valve = SceneItem('Valves', position, iobject)
            objects['Valves'].append(item_valve)

        # un tubo de entrada, valvula, cilindro, valvula y tubo de salida por cada cilindro
        for icyl in range(0, ncyls):
            iobject = copy.deepcopy(default_dict['Tubes'])
            iobject['tright'] = 'cylinder'
            iobject['tleft'] = 'tank'
            iobject['nright'] = icyl
            iobject['nleft'] = 0
            iobject['label'] = 'Tube_%s' % len(objects['Tubes'])
            configure_default_tube(iobject)
            position = QtCore.QPoint(X_SIZE * 5, Y_SIZE * icyl * 2)
            item_tube = SceneItem('Tubes', position, iobject)
            objects['Tubes'].append(item_tube)
            index_tube = objects['Tubes'].index(item_tube)
            objects['Tanks'][0].object['exh2tube'].append(index_tube)
            objects['Valves'][icyl].object['tube'] = index_tube

            if self.ui_ncd.default_cylinder.isChecked():
                lct = load_cylinder_template(default_dict['Configurations']['nstroke'],\
                                                    int(self.ui_ncd.type_ig.currentIndex()))
                if lct != {}:
                    iobject = lct
                else:
                    return False
            else:
                iobject = copy.deepcopy(default_dict['Cylinders'])
                # atributos de los objetos (todos iguales)
                iobject['type_ig'] = int(self.ui_ncd.type_ig.currentIndex())
                iobject['Bore'] = float(self.ui_ncd.Bore.text()) * MM2M
                iobject['crank_radius'] = float(
                    self.ui_ncd.crank_radius.text()) * MM2M / 2.0
                iobject['rod_length'] = float(
                    self.ui_ncd.rod_length.text()) * MM2M
                val = (0.5 * math.pi *
                       (float(self.ui_ncd.Bore.text()) * MM2M)**2 *
                       float(self.ui_ncd.crank_radius.text()) / 2.0 * MM2M)
                val = val / (float(self.ui_ncd.Vol_clearance.text()) - 1.0)
                iobject['Vol_clearance'] = val
                iobject['head_chamber_area'] = (math.pi * iobject['Bore']**2 /
                                                4.0) * 1.2
                iobject['piston_area'] = (math.pi * iobject['Bore']**2 /
                                          4.0) * 1.1

            iobject['label'] = 'Cylinder_%s' % icyl
            # state ini son 3 siempre (valvula int, cilindro, valvula ext)
            iobject['state_ini'] = [[1.1769, 101330.0, 300.0],
                                    [1.1769, 0.1, 101330.0],
                                    [1.1769, 0.1, 101330.0]]
            iobject['nnod'] = 3

            vol_constant = float(self.ui_ncd.vol_constant.text())
            objects['Tanks'][0].object['Volume'] = (
                vol_constant * math.pi * iobject['Bore']**2 /
                4.0) * iobject['crank_radius']

            position = QtCore.QPoint(X_SIZE * 8, Y_SIZE * icyl * 2)
            item_cyl = SceneItem('Cylinders', position, iobject)
            objects['Cylinders'].append(item_cyl)

            iobject = copy.deepcopy(default_dict['Valves'])
            iobject['ncyl'] = icyl
            iobject['typeVal'] = 'exh'
            iobject['label'] = 'Exhaust_Valve_%s' % icyl
            configure_default_valve(iobject,
                                    default_dict['Configurations']['nstroke'])
            position = QtCore.QPoint(X_SIZE * 9, Y_SIZE * icyl * 2)
            item_valve = SceneItem('Valves', position, iobject)
            objects['Valves'].append(item_valve)

            iobject = copy.deepcopy(default_dict['Tubes'])
            iobject['tright'] = 'junction'
            iobject['tleft'] = 'cylinder'
            iobject['nright'] = 0
            iobject['nleft'] = icyl
            iobject['label'] = 'Tube_%s' % len(objects['Tubes'])
            configure_default_tube(iobject)
            position = QtCore.QPoint(X_SIZE * 11, Y_SIZE * icyl * 2)
            item_tube = SceneItem('Tubes', position, iobject)
            objects['Junctions'][0].object['type_end'].append(1)
            objects['Tubes'].append(item_tube)
            index_tube = objects['Tubes'].index(item_tube)
            objects['Junctions'][0].object['node2tube'].append(index_tube)

            objects['Valves'][-1].object['tube'] = index_tube

        iobject = copy.deepcopy(default_dict['Tubes'])
        iobject['tright'] = 'atmosphere'
        iobject['tleft'] = 'junction'
        iobject['nright'] = 1
        iobject['nleft'] = 0
        iobject['label'] = 'Tube_%s' % len(objects['Tubes'])
        configure_default_tube(iobject)
        position = QtCore.QPoint(X_SIZE * 14, INITIAL_Y)
        item_tube = SceneItem('Tubes', position, iobject)
        objects['Tubes'].append(item_tube)
        index_tube = objects['Tubes'].index(item_tube)
        objects['Junctions'][0].object['type_end'].append(-1)
        objects['Junctions'][0].object['node2tube'].append(index_tube)

        iobject = copy.deepcopy(default_dict['Atmospheres'])
        position = QtCore.QPoint(X_SIZE * 16, INITIAL_Y)
        item_atmosphere = SceneItem('Atmospheres', position, iobject)
        objects['Atmospheres'].append(item_atmosphere)

        for ikey in objects.keys():
            for iobject in objects[ikey]:
                iobject.position = iobject.position + QtCore.QPoint(1.5, 1.5)
                iobject.pixmap.setPos(iobject.position)

        save_data_aux(cw,
                      objects,
                      self.case_dir,
                      self.case_name,
                      filename=None,
                      wizard=True)
        return True