signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def get_int_relative(strings: Sequence[str],<EOL>prefix1: str,<EOL>delta: int,<EOL>prefix2: str,<EOL>ignoreleadingcolon: bool = False) -> Optional[int]: | return get_int_raw(get_string_relative(<EOL>strings, prefix1, delta, prefix2,<EOL>ignoreleadingcolon=ignoreleadingcolon))<EOL> | Fetches an int parameter via :func:`get_string_relative`. | f14694:m14 |
def get_datetime(strings: Sequence[str],<EOL>prefix: str,<EOL>datetime_format_string: str,<EOL>ignoreleadingcolon: bool = False,<EOL>precedingline: str = "<STR_LIT>") -> Optional[datetime.datetime]: | x = get_string(strings, prefix, ignoreleadingcolon=ignoreleadingcolon,<EOL>precedingline=precedingline)<EOL>if len(x) == <NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>d = datetime.datetime.strptime(x, datetime_format_string)<EOL>return d<EOL> | Fetches a ``datetime.datetime`` parameter via :func:`get_string`. | f14694:m15 |
def find_line_beginning(strings: Sequence[str],<EOL>linestart: Optional[str]) -> int: | if linestart is None: <EOL><INDENT>for i in range(len(strings)):<EOL><INDENT>if is_empty_string(strings[i]):<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return -<NUM_LIT:1><EOL><DEDENT>for i in range(len(strings)):<EOL><INDENT>if strings[i].find(linestart) == <NUM_LIT:0>:<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return -... | Finds the index of the line in ``strings`` that begins with ``linestart``,
or ``-1`` if none is found.
If ``linestart is None``, match an empty line. | f14694:m16 |
def find_line_containing(strings: Sequence[str], contents: str) -> int: | for i in range(len(strings)):<EOL><INDENT>if strings[i].find(contents) != -<NUM_LIT:1>:<EOL><INDENT>return i<EOL><DEDENT><DEDENT>return -<NUM_LIT:1><EOL> | Finds the index of the line in ``strings`` that contains ``contents``,
or ``-1`` if none is found. | f14694:m17 |
def get_lines_from_to(strings: List[str],<EOL>firstlinestart: str,<EOL>list_of_lastline_starts: Iterable[Optional[str]])-> List[str]: | start_index = find_line_beginning(strings, firstlinestart)<EOL>if start_index == -<NUM_LIT:1>:<EOL><INDENT>return []<EOL><DEDENT>end_offset = None <EOL>for lls in list_of_lastline_starts:<EOL><INDENT>possible_end_offset = find_line_beginning(strings[start_index:], lls)<EOL>if possible_end_offset != -<NUM_LIT:1>: <EOL... | Takes a list of ``strings``. Returns a list of strings FROM
``firstlinestart`` (inclusive) TO the first of ``list_of_lastline_starts``
(exclusive).
To search to the end of the list, use ``list_of_lastline_starts = []``.
To search to a blank line, use ``list_of_lastline_starts = [None]`` | f14694:m18 |
def is_empty_string(s: str) -> bool: | return len(s.strip()) == <NUM_LIT:0><EOL> | Is the string empty (ignoring whitespace)? | f14694:m19 |
def csv_to_list_of_fields(lines: List[str],<EOL>csvheader: str,<EOL>quotechar: str = '<STR_LIT:">') -> List[str]: | <EOL>= [] <EOL>empty line marks the end of the block<EOL>nes = get_lines_from_to(lines, csvheader, [None])[<NUM_LIT:1>:]<EOL><INDENT>remove the CSV header<EOL><DEDENT>r = csv.reader(csvlines, quotechar=quotechar)<EOL>ields in reader:<EOL>ata.append(fields)<EOL>n data<EOL> | Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Used for processing e.g. MonkeyCantab rescue text output.
Args:
lines: CSV lines
csvheader: CSV header line
quotechar: ``quotechar`` parameter passed to :func:`csv.rea... | f14694:m20 |
def csv_to_list_of_dicts(lines: List[str],<EOL>csvheader: str,<EOL>quotechar: str = '<STR_LIT:">') -> List[Dict[str, str]]: | data = [] <EOL>csvlines = get_lines_from_to(lines, csvheader, [None])[<NUM_LIT:1>:]<EOL>headerfields = csvheader.split("<STR_LIT:U+002C>")<EOL>reader = csv.reader(csvlines, quotechar=quotechar)<EOL>for fields in reader:<EOL><INDENT>row = {} <EOL>for f in range(len(headerfields)):<EOL><INDENT>row[headerfields[f]] = fi... | Extracts data from a list of CSV lines (starting with a defined header
line) embedded in a longer text block but ending with a blank line.
Args:
lines: CSV lines
csvheader: CSV header line
quotechar: ``quotechar`` parameter passed to :func:`csv.reader`
Returns:
list of dictionaries mapping fieldnames ... | f14694:m21 |
def dictlist_convert_to_string(dict_list: Iterable[Dict], key: str) -> None: | for d in dict_list:<EOL><INDENT>d[key] = str(d[key])<EOL>if d[key] == "<STR_LIT>":<EOL><INDENT>d[key] = None<EOL><DEDENT><DEDENT> | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a string form, ``str(d[key])``. If the result is a
blank string, convert it to ``None``. | f14694:m22 |
def dictlist_convert_to_datetime(dict_list: Iterable[Dict],<EOL>key: str,<EOL>datetime_format_string: str) -> None: | for d in dict_list:<EOL><INDENT>d[key] = datetime.datetime.strptime(d[key], datetime_format_string)<EOL><DEDENT> | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a ``datetime.datetime`` form, using
``datetime_format_string`` as the format parameter to
:func:`datetime.datetime.strptime`. | f14694:m23 |
def dictlist_convert_to_int(dict_list: Iterable[Dict], key: str) -> None: | for d in dict_list:<EOL><INDENT>try:<EOL><INDENT>d[key] = int(d[key])<EOL><DEDENT>except ValueError:<EOL><INDENT>d[key] = None<EOL><DEDENT><DEDENT> | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to an integer. If that fails, convert it to ``None``. | f14694:m24 |
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None: | for d in dict_list:<EOL><INDENT>try:<EOL><INDENT>d[key] = float(d[key])<EOL><DEDENT>except ValueError:<EOL><INDENT>d[key] = None<EOL><DEDENT><DEDENT> | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a float. If that fails, convert it to ``None``. | f14694:m25 |
def dictlist_convert_to_bool(dict_list: Iterable[Dict], key: str) -> None: | for d in dict_list:<EOL><INDENT>d[key] = <NUM_LIT:1> if d[key] == "<STR_LIT:Y>" else <NUM_LIT:0><EOL><DEDENT> | Process an iterable of dictionaries. For each dictionary ``d``, convert
(in place) ``d[key]`` to a bool. If that fails, convert it to ``None``. | f14694:m26 |
def dictlist_replace(dict_list: Iterable[Dict], key: str, value: Any) -> None: | for d in dict_list:<EOL><INDENT>d[key] = value<EOL><DEDENT> | Process an iterable of dictionaries. For each dictionary ``d``, change
(in place) ``d[key]`` to ``value``. | f14694:m27 |
def dictlist_wipe_key(dict_list: Iterable[Dict], key: str) -> None: | for d in dict_list:<EOL><INDENT>d.pop(key, None)<EOL><DEDENT> | Process an iterable of dictionaries. For each dictionary ``d``, delete
``d[key]`` if it exists. | f14694:m28 |
def recursive_update(default, custom): | if not isinstance(default, dict) or not isinstance(custom, dict):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>for key in custom:<EOL><INDENT>if isinstance(custom[key], dict) and isinstance(<EOL>default.get(key), dict):<EOL><INDENT>default[key] = recursive_update(default[key], custom[key])<EOL><DEDENT>else:<EOL... | Return a dict merged from default and custom
>>> recursive_update('a', 'b')
Traceback (most recent call last):
...
TypeError: Params of recursive_update should be dicts
>>> recursive_update({'a': [1]}, {'a': [2], 'c': {'d': {'c': 3}}})
{'a': [2], 'c': {'d': {'c': 3}}}
>>> recursive_up... | f14699:m0 |
@staticmethod<EOL><INDENT>def save_to_db(model_text_id, parsed_values):<DEDENT> | Model = apps.get_model(model_text_id)<EOL>simple_fields = {}<EOL>many2many_fields = {}<EOL>for field, value in parsed_values.items():<EOL><INDENT>if (Model._meta.get_field(<EOL>field).get_internal_type() == '<STR_LIT>'):<EOL><INDENT>many2many_fields[field] = value<EOL><DEDENT>elif (Model._meta.get_field(<EOL>field).get... | save to db and return saved object | f14704:c0:m1 |
def apply_patch(diffs): | pass<EOL>if isinstance(diffs, patch.diff):<EOL><INDENT>diffs = [diffs]<EOL><DEDENT>for diff in diffs:<EOL><INDENT>if diff.header.old_path == '<STR_LIT>':<EOL><INDENT>text = []<EOL><DEDENT>else:<EOL><INDENT>with open(diff.header.old_path) as f:<EOL><INDENT>text = f.read()<EOL><DEDENT><DEDENT>new_text = apply_diff(diff, ... | Not ready for use yet | f14721:m0 |
@temporary_store_decorator(config_files_directory = config_files_directory, file_name = '<STR_LIT>')<EOL>def build_imputation_loyers_proprietaires(temporary_store = None, year = None): | assert temporary_store is not None<EOL>assert year is not None<EOL>bdf_survey_collection = SurveyCollection.load(collection = '<STR_LIT>',<EOL>config_files_directory = config_files_directory)<EOL>survey = bdf_survey_collection.get_survey('<STR_LIT>'.format(year))<EOL>if year == <NUM_LIT>:<EOL><INDENT>imput00 = survey.g... | Build menage consumption by categorie fiscale dataframe | f14723:m0 |
@temporary_store_decorator(config_files_directory = config_files_directory, file_name = '<STR_LIT>')<EOL>def build_homogeneisation_caracteristiques_sociales(temporary_store = None, year = None): | assert temporary_store is not None<EOL>assert year is not None<EOL>bdf_survey_collection = SurveyCollection.load(<EOL>collection = '<STR_LIT>', config_files_directory = config_files_directory)<EOL>survey = bdf_survey_collection.get_survey('<STR_LIT>'.format(year))<EOL>if year == <NUM_LIT>:<EOL><INDENT>kept_variables = ... | Homogénéisation des caractéristiques sociales des ménages | f14725:m0 |
def collapsesum(data_frame, by = None, var = None): | assert by is not None<EOL>assert var is not None<EOL>grouped = data_frame.groupby([by])<EOL>return grouped.apply(lambda x: weighted_sum(groupe = x, var =var))<EOL> | Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. | f14727:m0 |
def weighted_sum(groupe, var): | data = groupe[var]<EOL>weights = groupe['<STR_LIT>']<EOL>return (data * weights).sum()<EOL> | Fonction qui calcule la moyenne pondérée par groupe d'une variable | f14727:m2 |
@temporary_store_decorator(config_files_directory = config_files_directory, file_name = '<STR_LIT>')<EOL>def build_depenses_homogenisees(temporary_store = None, year = None): | assert temporary_store is not None<EOL>assert year is not None<EOL>bdf_survey_collection = SurveyCollection.load(<EOL>collection = '<STR_LIT>', config_files_directory = config_files_directory<EOL>)<EOL>survey = bdf_survey_collection.get_survey('<STR_LIT>'.format(year))<EOL>if year == <NUM_LIT>:<EOL><INDENT>socioscm = s... | Build menage consumption by categorie fiscale dataframe | f14728:m0 |
def normalize_code_coicop(code): | <EOL>try:<EOL><INDENT>code = unicode(code)<EOL><DEDENT>except:<EOL><INDENT>code = code<EOL><DEDENT>if len(code) == <NUM_LIT:3>:<EOL><INDENT>code_coicop = "<STR_LIT:0>" + code + "<STR_LIT:0>" <EOL><DEDENT>elif len(code) == <NUM_LIT:4>:<EOL><INDENT>if not code.startswith("<STR_LIT:0>") and not code.startswith("<STR_LIT:... | Normalize_coicop est function d'harmonisation de la colonne d'entiers posteCOICOP de la table
matrice_passage_data_frame en la transformant en une chaine de 5 caractères afin de pouvoir par la suite agréger les postes
COICOP selon les 12 postes agrégés de la nomenclature de la comptabilité nationale. Chaque poste conti... | f14728:m1 |
def preprocess_legislation(legislation_json): | import os<EOL>import pkg_resources<EOL>import pandas as pd<EOL>default_config_files_directory = os.path.join(<EOL>pkg_resources.get_distribution('<STR_LIT>').location)<EOL>prix_annuel_carburants = pd.read_csv(<EOL>os.path.join(<EOL>default_config_files_directory,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'... | Preprocess the legislation parameters to add prices and amounts from national accounts | f14731:m0 |
def droit_d_accise(depense, droit_cn, consommation_cn, taux_plein_tva): | return depense * ((<NUM_LIT:1> + taux_plein_tva) * droit_cn) / (consommation_cn - (<NUM_LIT:1> + taux_plein_tva) * droit_cn)<EOL> | Calcule le montant de droit d'accise sur un volume de dépense payé pour le poste adéquat. | f14744:m0 |
def taux_implicite(accise, tva, prix_ttc): | return (accise * (<NUM_LIT:1> + tva)) / (prix_ttc - accise * (<NUM_LIT:1> + tva))<EOL> | Calcule le taux implicite sur les carburants : pttc = pht * (1+ti) * (1+tva), ici on obtient ti | f14744:m1 |
def tax_from_expense_including_tax(expense = None, tax_rate = None): | return expense * tax_rate / (<NUM_LIT:1> + tax_rate)<EOL> | Compute the tax amount form the expense including tax : si Dttc = (1+t) * Dht, ici on obtient t * Dht | f14744:m2 |
def simulate(simulated_variables, year): | input_data_frame = get_input_data_frame(year)<EOL>TaxBenefitSystem = openfisca_france_indirect_taxation.init_country()<EOL>tax_benefit_system = TaxBenefitSystem()<EOL>survey_scenario = SurveyScenario().init_from_data_frame(<EOL>input_data_frame = input_data_frame,<EOL>tax_benefit_system = tax_benefit_system,<EOL>year =... | Construction de la DataFrame à partir de laquelle sera faite l'analyse des données | f14772:m1 |
def simulate_df_calee_by_grosposte(simulated_variables, year): | input_data_frame = get_input_data_frame(year)<EOL>input_data_frame_calee = build_df_calee_on_grospostes(input_data_frame, year, year)<EOL>TaxBenefitSystem = openfisca_france_indirect_taxation.init_country()<EOL>tax_benefit_system = TaxBenefitSystem()<EOL>survey_scenario = SurveyScenario().init_from_data_frame(<EOL>inpu... | Construction de la DataFrame à partir de laquelle sera faite l'analyse des données | f14772:m2 |
def simulate_df_calee_on_ticpe(simulated_variables, year): | input_data_frame = get_input_data_frame(year)<EOL>input_data_frame_calee = build_df_calee_on_ticpe(input_data_frame, year, year)<EOL>TaxBenefitSystem = openfisca_france_indirect_taxation.init_country()<EOL>tax_benefit_system = TaxBenefitSystem()<EOL>survey_scenario = SurveyScenario().init_from_data_frame(<EOL>input_dat... | Construction de la DataFrame à partir de laquelle sera faite l'analyse des données | f14772:m3 |
def wavg(groupe, var): | d = groupe[var]<EOL>w = groupe['<STR_LIT>']<EOL>return (d * w).sum() / w.sum()<EOL> | Fonction qui calcule la moyenne pondérée par groupe d'une variable | f14772:m4 |
def collapse(dataframe, groupe, var): | grouped = dataframe.groupby([groupe])<EOL>var_weighted_grouped = grouped.apply(lambda x: wavg(groupe = x, var = var))<EOL>return var_weighted_grouped<EOL> | Pour une variable, fonction qui calcule la moyenne pondérée au sein de chaque groupe. | f14772:m5 |
def df_weighted_average_grouped(dataframe, groupe, varlist): | return DataFrame(<EOL>dict([<EOL>(var, collapse(dataframe, groupe, var)) for var in varlist<EOL>])<EOL>)<EOL> | Agrège les résultats de weighted_average_grouped() en une unique dataframe pour la liste de variable 'varlist'. | f14772:m6 |
def calcul_ratios_calage(year_data, year_calage, data_bdf, data_cn): | masses = data_cn.merge(<EOL>data_bdf, left_index = True, right_index = True<EOL>)<EOL>masses.rename(columns = {<NUM_LIT:0>: '<STR_LIT>'.format(year_data)}, inplace = True)<EOL>if year_calage != year_data:<EOL><INDENT>masses['<STR_LIT>'.format(year_data, year_calage)] = (<EOL>masses['<STR_LIT>'.format(year_calage)] / ma... | Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf. | f14773:m1 |
def get_inflators_bdf_to_cn(data_year): | data_cn = get_cn_aggregates(data_year)<EOL>data_bdf = get_bdf_aggregates(data_year)<EOL>masses = data_cn.merge(<EOL>data_bdf, left_index = True, right_index = True<EOL>)<EOL>masses.rename(columns = {'<STR_LIT>': '<STR_LIT>'.format(data_year)}, inplace = True)<EOL>return (<EOL>masses['<STR_LIT>'.format(data_year)] / mas... | Calcule les ratios de calage (bdf sur cn pour année de données)
à partir des masses de comptabilité nationale et des masses de consommation de bdf. | f14774:m2 |
def get_inflators_cn_to_cn(target_year): | data_year = find_nearest_inferior(data_years, target_year)<EOL>data_year_cn_aggregates = get_cn_aggregates(data_year)['<STR_LIT>'.format(data_year)].to_dict()<EOL>target_year_cn_aggregates = get_cn_aggregates(target_year)['<STR_LIT>'.format(target_year)].to_dict()<EOL>return dict(<EOL>(key, target_year_cn_aggregates[ke... | Calcule l'inflateur de vieillissement à partir des masses de comptabilité nationale. | f14774:m3 |
def get_inflators(target_year): | data_year = find_nearest_inferior(data_years, target_year)<EOL>inflators_bdf_to_cn = get_inflators_bdf_to_cn(data_year)<EOL>inflators_cn_to_cn = get_inflators_cn_to_cn(target_year)<EOL>ratio_by_variable = dict()<EOL>for key in inflators_cn_to_cn.keys():<EOL><INDENT>ratio_by_variable[key] = inflators_bdf_to_cn[key] * in... | Fonction qui calcule les ratios de calage (bdf sur cn pour année de données) et de vieillissement
à partir des masses de comptabilité nationale et des masses de consommation de bdf. | f14774:m4 |
def init_tax_benefit_system(): | TaxBenefitSystem = init_country()<EOL>tax_benefit_system = TaxBenefitSystem()<EOL>return tax_benefit_system<EOL> | Helper function which suits most of the time.
Use `init_country` if you need to get the `TaxBenefitSystem` class. | f14797:m1 |
def __init__(self, filename, swapyz=False): | self.objects = {}<EOL>self.vertices = []<EOL>self.normals = []<EOL>self.texcoords = []<EOL>self.faces = []<EOL>self._current_object = None<EOL>material = None<EOL>for line in open(filename, "<STR_LIT:r>"):<EOL><INDENT>if line.startswith('<STR_LIT:#>'):<EOL><INDENT>continue<EOL><DEDENT>if line.startswith('<STR_LIT:s>'):... | Loads a Wavefront OBJ file. | f14835:c1:m1 |
def lerp(vecA, vecB, time): | return (vecA * time) + (vecB * (<NUM_LIT:1.0> - time))<EOL> | Linear interpolation between two vectors.
Function from pyGameMath: https://github.com/explosiveduck/pyGameMath | f14842:m0 |
def __init__(self, texture, *args, **kwargs): | super(FBO, self).__init__(*args, **kwargs)<EOL>self.id = create_opengl_object(gl.glGenFramebuffersEXT)<EOL>self._old_viewport = get_viewport()<EOL>self.texture = texture<EOL>self.renderbuffer = RenderBuffer(texture.width, texture.height) if not isinstance(texture, DepthTexture) else None<EOL>with self:<EOL><INDENT>self... | A Framebuffer object, which when bound redirects draws to its texture. This is useful for deferred rendering. | f14848:c0:m0 |
def bind(self): | <EOL>gl.glBindTexture(gl.GL_TEXTURE_2D, <NUM_LIT:0>)<EOL>self._old_viewport = get_viewport()<EOL>gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, self.id) <EOL>gl.glViewport(<NUM_LIT:0>, <NUM_LIT:0>, self.texture.width, self.texture.height)<EOL> | Bind the FBO. Anything drawn afterward will be stored in the FBO's texture. | f14848:c0:m1 |
def unbind(self): | <EOL>if self.texture.mipmap:<EOL><INDENT>with self.texture:<EOL><INDENT>self.texture.generate_mipmap()<EOL><DEDENT><DEDENT>gl.glBindFramebufferEXT(gl.GL_FRAMEBUFFER_EXT, <NUM_LIT:0>)<EOL>gl.glViewport(*self._old_viewport)<EOL> | Unbind the FBO. | f14848:c0:m2 |
def __init__(self, parent=None, children=None, **kwargs): | super(SceneGraph, self).__init__(**kwargs)<EOL>self._children = []<EOL>self._parent = None<EOL>if parent:<EOL><INDENT>self.parent = parent<EOL><DEDENT>if children:<EOL><INDENT>self.add_children(children)<EOL><DEDENT> | A Node of the Scenegraph. Has children, but no parent. | f14850:c0:m0 |
def __iter__(self): | def walk_tree_breadthfirst(obj):<EOL><INDENT>"""<STR_LIT>"""<EOL>order = deque([obj])<EOL>while len(order) > <NUM_LIT:0>:<EOL><INDENT>order.extend(order[<NUM_LIT:0>]._children)<EOL>yield order.popleft()<EOL><DEDENT><DEDENT>return walk_tree_breadthfirst(self)<EOL> | Returns an iterator that walks through the scene graph,
starting with the current object. | f14850:c0:m1 |
@property<EOL><INDENT>def parent(self):<EOL><DEDENT> | return self._parent<EOL> | A SceneNode object that is this object's parent in the scene graph. | f14850:c0:m2 |
def add_child(self, child): | if not issubclass(child.__class__, SceneGraph):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>child._parent = self<EOL>self._children.append(child)<EOL> | Adds an object as a child in the scene graph. | f14850:c0:m4 |
def add_children(self, *children, **kwargs): | for child in children:<EOL><INDENT>self.add_child(child, **kwargs)<EOL><DEDENT> | Conveniience function: Adds objects as children in the scene graph. | f14850:c0:m5 |
def __init__(self, position=(<NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:0.>), rotation=(<NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:0.>), scale=<NUM_LIT:1.>, orientation0=(<NUM_LIT:1.>, <NUM_LIT:0.>, <NUM_LIT:0.>),<EOL>**kwargs): | super(Physical, self).__init__(**kwargs)<EOL>self.orientation0 = np.array(orientation0, dtype=np.float32)<EOL>self.rotation = coordinates.RotationEulerDegrees(*rotation)<EOL>self.position = coordinates.Translation(*position)<EOL>if hasattr(scale, '<STR_LIT>'):<EOL><INDENT>if <NUM_LIT:0> in scale:<EOL><INDENT>raise Valu... | XYZ Position, Scale and XYZEuler Rotation Class.
Args:
position: (x, y, z) translation values.
rotation: (x, y, z) rotation values
scale (float): uniform scale factor. 1 = no scaling. | f14852:c0:m0 |
@property<EOL><INDENT>def orientation0(self):<DEDENT> | return self._orientation0<EOL> | Starting orientation (3-element unit vector). New orientations are calculated by rotating from this vector. | f14852:c0:m13 |
@property<EOL><INDENT>def orientation(self):<DEDENT> | return self.rotation.rotate(self.orientation0)<EOL> | The object's orientation as a vector, calculated by rotation from orientation0, the starting orientation. | f14852:c0:m15 |
def look_at(self, x, y, z): | new_ori = x - self.position.x, y - self.position.y, z - self.position.z<EOL>self.orientation = new_ori / np.linalg.norm(new_ori)<EOL> | Rotate so orientation is toward (x, y, z) coordinates. | f14852:c0:m17 |
def __init__(self, **kwargs): | self._model_matrix_global = np.identity(<NUM_LIT:4>, dtype=np.float32)<EOL>self._normal_matrix_global = np.identity(<NUM_LIT:4>, dtype=np.float32)<EOL>self._view_matrix_global = np.identity(<NUM_LIT:4>, dtype=np.float32)<EOL>self._model_matrix_transform = np.identity(<NUM_LIT:4>, dtype=np.float32)<EOL>self._normal_matr... | Object with xyz position and rotation properties that are relative to its parent. | f14852:c1:m0 |
def add_child(self, child, modify=False): | SceneGraph.add_child(self, child)<EOL>self.notify()<EOL>if modify:<EOL><INDENT>child._model_matrix_transform[:] = trans.inverse_matrix(self.model_matrix_global)<EOL>child._normal_matrix_transform[:] = trans.inverse_matrix(self.normal_matrix_global)<EOL><DEDENT> | Adds an object as a child in the scene graph. With modify=True, model_matrix_transform gets change from identity and prevents the changes of the coordinates of the child | f14852:c1:m9 |
@property<EOL><INDENT>def orientation_global(self):<DEDENT> | return self.rotation_global.rotate(self.orientation0)<EOL> | Orientation vector, in world coordinates. | f14852:c1:m12 |
def __init__(self, z_near=<NUM_LIT:0.1>, z_far=<NUM_LIT>, **kwargs): | super(ProjectionBase, self).__init__(**kwargs)<EOL>self._projection_matrix = np.identity(<NUM_LIT:4>, dtype=np.float32)<EOL>if z_near >= z_far or z_near <= <NUM_LIT:0.> or z_far <= <NUM_LIT:0.>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._z_near = z_near<EOL>self._z_far = z_far<EOL>self._update_projecti... | Abstract Base Class for the Projections. Used to create projectoin matrix that later represents Camera Space.
Vertex with position=(0,0,0), should be located in the middle of the scene. Projection matrix has defined z - distance to the camera.
Args:
z_near (float): the nearest distance to the camera, has to be pos... | f14853:c0:m0 |
@property<EOL><INDENT>def projection_matrix(self):<DEDENT> | return self._projection_matrix.view()<EOL> | Return projection_matrix | f14853:c0:m1 |
@property<EOL><INDENT>def z_near(self):<DEDENT> | return self._z_near<EOL> | Return z_near value | f14853:c0:m3 |
@property<EOL><INDENT>def z_far(self):<DEDENT> | return self._z_far<EOL> | Return z_far value | f14853:c0:m5 |
def update(self): | self._update_projection_matrix()<EOL> | Updates projection matrix | f14853:c0:m8 |
@property<EOL><INDENT>def viewport(self):<DEDENT> | return get_viewport()<EOL> | returns the viewport | f14853:c0:m9 |
def copy(self): | params = {}<EOL>for key, val in self.__dict__.items():<EOL><INDENT>if '<STR_LIT>' not in key:<EOL><INDENT>k = key[<NUM_LIT:1>:] if key[<NUM_LIT:0>] == '<STR_LIT:_>' else key<EOL>params[k] = val<EOL><DEDENT><DEDENT>return self.__class__(**params)<EOL> | Returns a copy of the projection matrix | f14853:c0:m10 |
def __init__(self, origin='<STR_LIT>', coords='<STR_LIT>', **kwargs): | self._origin = origin<EOL>self._coords = coords<EOL>super(OrthoProjection, self).__init__(**kwargs)<EOL> | Orthogonal Projection Object cretes projection Object that can be used in Camera
Args:
origin (str): 'center' or 'corner'
coords (str): 'relative' or 'absolute'
Returns:
OrthoProjection instance | f14853:c1:m0 |
@property<EOL><INDENT>def origin(self):<DEDENT> | return self._origin<EOL> | Returns origin of the Projection | f14853:c1:m1 |
@property<EOL><INDENT>def coords(self):<DEDENT> | return self._coords<EOL> | Returns coordinates | f14853:c1:m3 |
def match_aspect_to_viewport(self): | viewport = self.viewport<EOL>self.aspect = float(viewport.width) / viewport.height<EOL> | Updates Camera.aspect to match the viewport's aspect ratio. | f14853:c2:m3 |
def _get_shift_matrix(self): | return np.array([[<NUM_LIT:1.>, <NUM_LIT:0.>, self.x_shift, <NUM_LIT:0.>],<EOL>[<NUM_LIT:0.>, <NUM_LIT:1.>, self.y_shift, <NUM_LIT:0.>],<EOL>[<NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.>, <NUM_LIT:0.>],<EOL>[<NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:1.>]], dtype=np.float32)<EOL> | np.array: The Camera's lens-shift matrix. | f14853:c2:m10 |
def _update_projection_matrix(self): | <EOL>ff = <NUM_LIT:1.>/np.tan(np.radians(self.fov_y / <NUM_LIT>)) <EOL>zn, zf = self.z_near, self.z_far<EOL>persp_mat = np.array([[ff/self.aspect, <NUM_LIT:0.>, <NUM_LIT:0.>, <NUM_LIT:0.>],<EOL>[ <NUM_LIT:0.>, ff, <NUM_LIT:0.>, <NUM_LIT:0.>],<... | np.array: The Camera's Projection Matrix. Will be an Orthographic matrix if ortho_mode is set to True. | f14853:c2:m11 |
def __init__(self, projection=None, orientation0=(<NUM_LIT:0>, <NUM_LIT:0>, -<NUM_LIT:1>), **kwargs): | kwargs['<STR_LIT>'] = orientation0<EOL>super(Camera, self).__init__(**kwargs)<EOL>self.projection = PerspectiveProjection() if not projection else projection<EOL>self.reset_uniforms()<EOL> | Returns a camera object
Args:
projection (obj): the projection type for the camera. It can either be an instance of OrthoProjection or PerspeectiveProjection
orientation0 (tuple):
Returns:
Camera instance | f14853:c3:m0 |
def to_pickle(self, filename): | with open(filename, '<STR_LIT:wb>') as f:<EOL><INDENT>pickle.dump(self, f)<EOL><DEDENT> | Save Camera to a pickle file, given a filename. | f14853:c3:m4 |
@classmethod<EOL><INDENT>def from_pickle(cls, filename):<DEDENT> | with open(filename, '<STR_LIT:rb>') as f:<EOL><INDENT>cam = pickle.load(f)<EOL><DEDENT>projection = cam.projection.copy()<EOL>return cls(projection=projection, position=cam.position.xyz, rotation=cam.rotation.__class__(*cam.rotation[:]))<EOL> | Loads and Returns a Camera from a pickle file, given a filename. | f14853:c3:m5 |
@property<EOL><INDENT>def projection(self):<DEDENT> | return self._projection<EOL> | Returns the Camera's Projection | f14853:c3:m6 |
@property<EOL><INDENT>def projection_matrix(self):<DEDENT> | return self.projection.projection_matrix.view()<EOL> | Returns projection matrix of the Camera | f14853:c3:m9 |
def __init__(self, cameras=None, *args, **kwargs): | super(CameraGroup, self).__init__(*args, **kwargs)<EOL>self.cameras = cameras<EOL>self.add_children(*self.cameras)<EOL> | Creates a group of cameras that behave dependently | f14853:c4:m0 |
def look_at(self, x, y, z): | for camera in self.cameras:<EOL><INDENT>camera.look_at(x, y, z)<EOL><DEDENT> | Converges the two cameras to look at the specific point | f14853:c4:m1 |
def __init__(self, distance=<NUM_LIT>, projection=None, convergence=<NUM_LIT:0.>, *args, **kwargs): | cameras = [Camera(projection=projection) for _ in range(<NUM_LIT:2>)]<EOL>super(StereoCameraGroup, self).__init__(cameras=cameras, *args, **kwargs)<EOL>for camera, x in zip(self.cameras, [-distance / <NUM_LIT:2>, distance / <NUM_LIT:2>]):<EOL><INDENT>project = projection.copy() if isinstance(projection, ProjectionBase)... | Creates a group of cameras that behave dependently | f14853:c5:m0 |
def cross_product_matrix(vec): | return np.array([[<NUM_LIT:0>, -vec[<NUM_LIT:2>], vec[<NUM_LIT:1>]],<EOL>[vec[<NUM_LIT:2>], <NUM_LIT:0>, -vec[<NUM_LIT:0>]],<EOL>[-vec[<NUM_LIT:1>], vec[<NUM_LIT:0>], <NUM_LIT:0>]])<EOL> | Returns a 3x3 cross-product matrix from a 3-element vector. | f14854:m0 |
def rotation_matrix_between_vectors(from_vec, to_vec): | a, b = (trans.unit_vector(vec) for vec in (from_vec, to_vec))<EOL>v = np.cross(a, b)<EOL>cos = np.dot(a, b)<EOL>if cos == -<NUM_LIT:1.>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>v_cpm = cross_product_matrix(v)<EOL>rot_mat = np.identity(<NUM_LIT:3>) + v_cpm + np.dot(v_cpm, v_cpm) * (<NUM_LIT:1.> / <NUM_LIT:... | Returns a rotation matrix to rotate from 3d vector "from_vec" to 3d vector "to_vec".
Equation from https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d | f14854:m1 |
def __init__(self, *args, **kwargs): | super(Coordinates, self).__init__(**kwargs)<EOL>self._array = np.array(args, dtype=np.float32)<EOL>self._init_coord_properties()<EOL> | Returns a Coordinates object | f14854:c0:m0 |
def _init_coord_properties(self): | def gen_getter_setter_funs(*args):<EOL><INDENT>indices = [self.coords[coord] for coord in args]<EOL>def getter(self):<EOL><INDENT>return tuple(self._array[indices]) if len(args) > <NUM_LIT:1> else self._array[indices[<NUM_LIT:0>]]<EOL><DEDENT>def setter(self, value):<EOL><INDENT>setitem(self._array, indices, value)<EOL... | Generates combinations of named coordinate values, mapping them to the internal array.
For Example: x, xy, xyz, y, yy, zyx, etc | f14854:c0:m2 |
def rotate(self, vector): | return np.dot(self.to_matrix()[:<NUM_LIT:3>, :<NUM_LIT:3>], vector).flatten()<EOL> | Takes a vector and returns it rotated by self. | f14854:c1:m4 |
def draw(self, *args, **kwargs): | pass<EOL> | Passes all given arguments | f14855:c0:m0 |
def reset_uniforms(self): | pass<EOL> | Passes alll given arguments | f14855:c0:m1 |
def __init__(self, arrays, textures=(), mean_center=True,<EOL>gl_states=(), drawmode=gl.GL_TRIANGLES, point_size=<NUM_LIT:15>, dynamic=False, visible=True, **kwargs): | super(Mesh, self).__init__(**kwargs)<EOL>self.reset_uniforms()<EOL>arrays = tuple(np.array(array, dtype=np.float32) for array in arrays)<EOL>self.arrays, self.array_indices = vertutils.reindex_vertices(arrays)<EOL>vertex_mean = self.arrays[<NUM_LIT:0>][self.array_indices, :].mean(axis=<NUM_LIT:0>)<EOL>if mean_center:<E... | Returns a Mesh object, containing the position, rotation, and color info of an OpenGL Mesh.
Meshes have two coordinate system, the "local" and "world" systems, on which the transforms are performed
sequentially. This allows them to be placed in the scene while maintaining a relative position to one another.
.. note:... | f14855:c1:m0 |
def copy(self): | return Mesh(arrays=deepcopy([arr.copy() for arr in [self.vertices, self.normals, self.texcoords]]), texture=self.textures, mean_center=deepcopy(self._mean_center),<EOL>position=self.position.xyz, rotation=self.rotation.__class__(*self.rotation[:]), scale=self.scale.xyz,<EOL>drawmode=self.drawmode, point_size=self.point... | Returns a copy of the Mesh. | f14855:c1:m2 |
def to_pickle(self, filename): | with open(filename, '<STR_LIT:wb>') as f:<EOL><INDENT>pickle.dump(self, f)<EOL><DEDENT> | Save Mesh to a pickle file, given a filename. | f14855:c1:m3 |
@classmethod<EOL><INDENT>def from_pickle(cls, filename):<DEDENT> | with open(filename, '<STR_LIT:rb>') as f:<EOL><INDENT>mesh = pickle.load(f).copy()<EOL><DEDENT>return mesh<EOL> | Loads and Returns a Mesh from a pickle file, given a filename. | f14855:c1:m4 |
def reset_uniforms(self): | self.uniforms['<STR_LIT>'] = self.model_matrix_global.view()<EOL>self.uniforms['<STR_LIT>'] = self.normal_matrix_global.view()<EOL> | Resets the uniforms to the Mesh object to the ""global"" coordinate system | f14855:c1:m5 |
@property<EOL><INDENT>def dynamic(self):<DEDENT> | return self._dynamic<EOL> | dynamic property of the mesh. If set to True, enables the user to modify vertices dynamically. | f14855:c1:m6 |
@property<EOL><INDENT>def vertices(self):<DEDENT> | return self.arrays[<NUM_LIT:0>][:, :<NUM_LIT:3>].view()<EOL> | Mesh vertices, centered around 0,0,0. | f14855:c1:m8 |
@property<EOL><INDENT>def normals(self):<DEDENT> | return self.arrays[<NUM_LIT:1>][:, :<NUM_LIT:3>].view()<EOL> | Mesh normals array. | f14855:c1:m10 |
@property<EOL><INDENT>def texcoords(self):<DEDENT> | return self.arrays[<NUM_LIT:2>][:, :<NUM_LIT:2>].view()<EOL> | UV coordinates | f14855:c1:m12 |
@property<EOL><INDENT>def vertices_local(self):<DEDENT> | return np.dot(self.model_matrix, self.vertices)<EOL> | Vertex position, in local coordinate space (modified by model_matrix) | f14855:c1:m14 |
@property<EOL><INDENT>def vertices_global(self):<DEDENT> | return np.dot(self.model_matrix_global, self.vertices)<EOL> | Vertex position, in world coordinate space (modified by model_matrix) | f14855:c1:m15 |
@classmethod<EOL><INDENT>def from_incomplete_data(cls, vertices, normals=(), texcoords=(), **kwargs):<DEDENT> | normals = normals if hasattr(texcoords, '<STR_LIT>') and len(normals) else vertutils.calculate_normals(vertices)<EOL>texcoords = texcoords if hasattr(texcoords, '<STR_LIT>') and len(texcoords) else np.zeros((vertices.shape[<NUM_LIT:0>], <NUM_LIT:2>), dtype=np.float32)<EOL>return cls(arrays=(vertices, normals, texcoords... | Return a Mesh with (vertices, normals, texcoords) as arrays, in that order.
Useful for when you want a standardized array location format across different amounts of info in each mesh. | f14855:c1:m18 |
def _fill_vao(self): | with self.vao:<EOL><INDENT>self.vbos = []<EOL>for loc, verts in enumerate(self.arrays):<EOL><INDENT>vbo = VBO(verts)<EOL>self.vbos.append(vbo)<EOL>self.vao.assign_vertex_attrib_location(vbo, loc)<EOL><DEDENT><DEDENT> | Put array location in VAO for shader in same order as arrays given to Mesh. | f14855:c1:m19 |
def draw(self): | if not self.vao:<EOL><INDENT>self.vao = VAO(indices=self.array_indices)<EOL>self._fill_vao()<EOL><DEDENT>if self.visible:<EOL><INDENT>if self.dynamic:<EOL><INDENT>for vbo in self.vbos:<EOL><INDENT>vbo._buffer_subdata()<EOL><DEDENT><DEDENT>if self.drawmode == gl.GL_POINTS:<EOL><INDENT>gl.glPointSize(self.point_size)<EOL... | Draw the Mesh if it's visible, from the perspective of the camera and lit by the light. The function sends the uniforms | f14855:c1:m20 |
def clear(self): | clear_color(*self.bgColor)<EOL> | Clear Screen and Apply Background Color | f14856:c0:m2 |
def draw(self, clear=True): | if clear:<EOL><INDENT>self.clear()<EOL><DEDENT>with self.gl_states, self.camera, self.light:<EOL><INDENT>for mesh in self.meshes:<EOL><INDENT>try:<EOL><INDENT>mesh.draw()<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT><DEDENT><DEDENT> | Draw each visible mesh in the scene from the perspective of the scene's camera and lit by its light. | f14856:c0:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.