| ID | \nFile Path | \nTimestamp | \n
|---|
\",\"\").replace(\"\",\"\")\n #print(data1)\n templist=[]\n for c in data1:\n templist.append(str(max(ord(c)%2,0)))\n print(\"\".join(templist))\n\n if data1 in lista:\n print(\"Match:\"+ data1)\n print(str(len(lista)))\n break;\n lista.append(data1)\n #if(len(lista)) > 500:\n # break;\n\n\"\"\"\ns = socket.socket()\ns.connect((\"https://dctf.def.camp/b4s1.php\", 80))\ndata=s.recv(1024)+s.recv(1024) \ndata=data.strip().split('\\n')\nprint(data)\n\n\n\"\"\"","repo_name":"matbrik/python-mix","sub_path":"Python Mix/Python Mix/cftChallanges/crc.py","file_name":"crc.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37310437837","text":"import sys\nfrom typing import Union\nimport numpy\nfrom vtkmodules.vtkCommonColor import vtkNamedColors, vtkColorSeries\nfrom vtkmodules.vtkCommonDataModel import vtkPointSet, vtkPolyData, vtkImageData\nfrom vtkmodules.vtkRenderingCore import (\n vtkActor,\n vtkMapper,\n vtkActorCollection,\n vtkTextActor, \n vtkProperty,\n vtkCellPicker,\n vtkPointPicker,\n vtkPolyDataMapper,\n vtkDataSetMapper,\n vtkRenderWindow,\n vtkRenderWindowInteractor,\n vtkRenderer,\n vtkColorTransferFunction,\n \n)\nfrom vtkmodules.vtkFiltersCore import vtkFeatureEdges, vtkExtractEdges, vtkIdFilter\nfrom vtkmodules.vtkFiltersGeneral import vtkCurvatures\nfrom vtkmodules.vtkCommonCore import vtkDataArray, vtkScalarsToColors, vtkCharArray, vtkLookupTable\nfrom vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera, vtkInteractorStyleTrackballActor, vtkInteractorStyleImage\nfrom vtkmodules.vtkRenderingCore import vtkProp, vtkInteractorStyle, vtkBillboardTextActor3D\nfrom vtk_bridge import *\nfrom .polydata import *\nfrom register import nicp # cannot run without this, don't know why\nfrom vtkmodules.util import numpy_support\nfrom vtkmodules.numpy_interface import dataset_adapter as dsa\n\n\ncolornames = ['IndianRed', 'LightSalmon', 'Pink', 'Gold', 'Lavender', 'GreenYellow', 'Aqua', 'Cornsilk', 'White', 'Gainsboro',\n 'LightCoral', 'Coral', 'LightPink', 'Yellow', 'Thistle', 'Chartreuse', 'Cyan', 'BlanchedAlmond', 'Snow', 'LightGrey',\n 'Salmon', 'Tomato', 'HotPink', 'LightYellow', 'Plum', 'LawnGreen', 'LightCyan', 'Bisque', 'Honeydew','Silver',\n 'DarkSalmon', 'OrangeRed', 'DeepPink', 'LemonChiffon', 'Violet', 'Lime', 'PaleTurquoise', 'NavajoWhite', 'MintCream',\n 'DarkGray', 'LightSalmon', 'DarkOrange', 'MediumVioletRed', 'LightGoldenrodYellow', 'Orchid', 'LimeGreen', 'Aquamarine', 'Wheat', 'Azure', 'Gray',\n 'Red', 'Orange', 'PaleVioletRed', 'PapayaWhip', 'Fuchsia', 'PaleGreen', 'Turquoise', 'BurlyWood', 'AliceBlue', 'DimGray', 'Crimson']\n\ncolors = vtkNamedColors()\ncolor_series = vtkColorSeries()\n\n# https://htmlpreview.github.io/?https://github.com/Kitware/vtk-examples/blob/gh-pages/VTKColorSeriesPatches.html\n\n\ndef build_colors(lower_bound, upper_bound, color_scheme_idx:int=15, colors_rgb:np.ndarray=None):\n\n if color_scheme_idx is not None:\n color_series = vtkColorSeries()\n color_series.SetColorScheme(color_scheme_idx)\n lookup_table = color_series.CreateLookupTable()\n\n elif colors_rgb is not None:\n lookup_table = vtkLookupTable()\n for i, (r,g,b) in enumerate(colors_rgb):\n lookup_table.SetTableValue(i,r,g,b)\n\n lookup_table.SetTableRange(lower_bound, upper_bound)\n lookup_table.Modified()\n lookup_table.Build()\n\n return lookup_table\n\n\ndef update_colors(lookup_table:vtkLookupTable, color_scheme_idx:int=None, colors_rgb:np.ndarray=None, lower_bound:float=None, upper_bound:float=None):\n\n if color_scheme_idx is not None:\n lookup_table.ResetAnnotations()\n color_series = vtkColorSeries()\n color_series.SetColorScheme(color_scheme_idx)\n color_series.BuildLookupTable(lookup_table)\n\n elif colors_rgb is not None:\n lookup_table.ResetAnnotations()\n for i, (r,g,b) in enumerate(colors_rgb):\n lookup_table.SetTableValue(i,r,g,b)\n \n if lower_bound is None:\n lower_bound = lookup_table.GetTableRange()[0]\n \n if upper_bound is None:\n upper_bound = lookup_table.GetTableRange()[1]\n\n lookup_table.SetTableRange(lower_bound, upper_bound)\n lookup_table.Modified()\n lookup_table.Build()\n\n return None\n\n\ndef map_scalars_through_table(lut:vtkScalarsToColors, scalars:Union[numpy.ndarray, vtkDataArray]) -> numpy.ndarray:\n if isinstance(scalars, numpy.ndarray):\n sc = scalars.flatten()\n rgba = numpy.empty(sc.size*4, \"uint8\")\n sc_vtk = numpy_to_vtk_(sc)\n shp = scalars.shape\n else:\n sc_vtk = scalars\n shp = (scalars.GetNumberOfTuples(),)\n rgba = numpy.empty(sc_vtk.GetNumberOfTuples()*4, \"uint8\")\n lut.MapScalarsThroughTable(sc_vtk, rgba)\n rgba = rgba.reshape(*shp,4)/255 #???????\n return rgba\n\n\n# def render_window(window_title=''):\n# renderer = vtkRenderer()\n# renderer.SetBackground(.67, .93, .93)\n\n# render_window = vtkRenderWindow()\n# render_window.AddRenderer(renderer)\n# render_window.SetSize(1000,1500)\n# render_window.SetWindowName(window_title)\n\n# interactor = vtkRenderWindowInteractor()\n# interactor.SetRenderWindow(render_window)\n\n# style = vtkInteractorStyleTrackballCamera()\n# style.SetDefaultRenderer(renderer)\n# interactor.SetInteractorStyle(style)\n# return interactor, renderer\n\n\ndef set_curvatures(polyd, curvature_name):\n\n def adjust_edge_curvatures(source, curvature_name, epsilon=1.0e-08):\n\n \"\"\"\n This function adjusts curvatures along the edges of the surface by replacing\n the value with the average value of the curvatures of points in the neighborhood.\n\n Remember to update the vtkCurvatures object before calling this.\n\n :param source: A vtkPolyData object corresponding to the vtkCurvatures object.\n :param curvature_name: The name of the curvature, 'Gauss_Curvature' or 'Mean_Curvature'.\n :param epsilon: Absolute curvature values less than this will be set to zero.\n :return:\n \"\"\"\n # https://examples.vtk.org/site/Python/PolyData/Curvatures/\n\n def point_neighbourhood(pt_id):\n \"\"\"\n Find the ids of the neighbours of pt_id.\n\n :param pt_id: The point id.\n :return: The neighbour ids.\n \"\"\"\n \"\"\"\n Extract the topological neighbors for point pId. In two steps:\n 1) source.GetPointCells(pt_id, cell_ids)\n 2) source.GetCellPoints(cell_id, cell_point_ids) for all cell_id in cell_ids\n \"\"\"\n cell_ids = vtkIdList()\n source.GetPointCells(pt_id, cell_ids)\n neighbour = set()\n for cell_idx in range(0, cell_ids.GetNumberOfIds()):\n cell_id = cell_ids.GetId(cell_idx)\n cell_point_ids = vtkIdList()\n source.GetCellPoints(cell_id, cell_point_ids)\n for cell_pt_idx in range(0, cell_point_ids.GetNumberOfIds()):\n neighbour.add(cell_point_ids.GetId(cell_pt_idx))\n return neighbour\n\n def compute_distance(pt_id_a, pt_id_b):\n \"\"\"\n Compute the distance between two points given their ids.\n\n :param pt_id_a:\n :param pt_id_b:\n :return:\n \"\"\"\n pt_a = np.array(source.GetPoint(pt_id_a))\n pt_b = np.array(source.GetPoint(pt_id_b))\n return np.linalg.norm(pt_a - pt_b)\n\n # Get the active scalars\n source.GetPointData().SetActiveScalars(curvature_name)\n curvatures = vtk_to_numpy_(source.GetPointData().GetScalars(curvature_name)).flatten().copy()\n\n # Get the boundary point IDs.\n array_name = 'ids'\n id_filter = vtkIdFilter()\n id_filter.SetInputData(source)\n id_filter.SetPointIds(True)\n id_filter.SetCellIds(False)\n id_filter.SetPointIdsArrayName(array_name)\n id_filter.SetCellIdsArrayName(array_name)\n id_filter.Update()\n\n edges = vtkFeatureEdges()\n edges.SetInputConnection(id_filter.GetOutputPort())\n edges.BoundaryEdgesOn()\n edges.ManifoldEdgesOff()\n edges.NonManifoldEdgesOff()\n edges.FeatureEdgesOff()\n edges.Update()\n\n edge_array = edges.GetOutput().GetPointData().GetArray(array_name)\n boundary_ids = []\n for i in range(edges.GetOutput().GetNumberOfPoints()):\n boundary_ids.append(edge_array.GetValue(i))\n # Remove duplicate Ids.\n p_ids_set = set(boundary_ids)\n\n # Iterate over the edge points and compute the curvature as the weighted\n # average of the neighbours.\n count_invalid = 0\n for p_id in boundary_ids:\n p_ids_neighbors = point_neighbourhood(p_id)\n # Keep only interior points.\n p_ids_neighbors -= p_ids_set\n # Compute distances and extract curvature values.\n curvs = [curvatures[p_id_n] for p_id_n in p_ids_neighbors]\n dists = [compute_distance(p_id_n, p_id) for p_id_n in p_ids_neighbors]\n curvs = np.array(curvs)\n dists = np.array(dists)\n curvs = curvs[dists > 0]\n dists = dists[dists > 0]\n if len(curvs) > 0:\n weights = 1 / np.array(dists)\n weights /= weights.sum()\n new_curv = np.dot(curvs, weights)\n else:\n # Corner case.\n count_invalid += 1\n # Assuming the curvature of the point is planar.\n new_curv = 0.0\n # Set the new curvature value.\n curvatures[p_id] = new_curv\n\n \n # Set small values to zero.\n if epsilon != 0.0:\n curvatures = np.where(abs(curvatures) < epsilon, 0, curvatures)\n\n curv = numpy_to_vtk(num_array=curvatures.ravel(), deep=True, array_type=VTK_DOUBLE)\n curv.SetName(curvature_name)\n\n return curv\n \n cc = vtkCurvatures()\n cc.SetInputData(polyd)\n if curvature_name == 'Mean_Curvature':\n cc.SetCurvatureTypeToMean()\n elif curvature_name == 'Gauss_Curvature':\n cc.SetCurvatureTypeToGaussian()\n else:\n raise ValueError('add support later')\n cc.Update()\n curv = cc.GetOutput().GetPointData().GetArray(curvature_name)\n # curv = adjust_edge_curvatures(cc.GetOutput(), curvature_name)\n\n if polyd.GetPointData().HasArray(curvature_name):\n polyd.GetPointData().RemoveArray(curvature_name)\n polyd.GetPointData().AddArray(curv)\n polyd.GetPointData().SetActiveScalars(curvature_name)\n return None\n\ndef polydata_actor(polyd:vtkPolyData, mapper=None, **property):\n if mapper is None:\n mapper = vtkPolyDataMapper()\n mapper.SetInputData(polyd)\n actor = vtkActor()\n actor.SetMapper(mapper)\n if property:\n for pk,pv in property.items():\n if pk=='Color':\n if isinstance(pv, int):\n pv = colornames[pv]\n if isinstance(pv, str):\n pv = colors.GetColor3d(pv)\n getattr(actor.GetProperty(),'Set'+pk).__call__(pv)\n\n return actor\n\n\ndef text_actor(coords:numpy.ndarray, label:str, font_size=24, color=(0,0,0), display_offset=(0,10), **text_property):\n if isinstance(color, str):\n color = colors.GetColor3d(color)\n\n actor = vtkBillboardTextActor3D()\n actor.SetPosition(coords)\n actor.SetInput(label)\n actor.SetDisplayOffset(*display_offset)\n actor.GetTextProperty().SetFontSize(font_size)\n actor.GetTextProperty().SetColor(color)\n actor.GetTextProperty().SetJustificationToCentered()\n actor.PickableOff()\n # actor.ForceOpaqueOn()\n if text_property:\n for pk,pv in text_property.items():\n getattr(actor.GetTextProperty(),'Set'+pk).__call__(pv)\n\n","repo_name":"kuangts/py-scripts","sub_path":"tools/_rendering.py","file_name":"_rendering.py","file_ext":"py","file_size_in_byte":11216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"29940316745","text":"from argparse import ArgumentParser\nimport glob\nimport logging\nimport os\nimport re\nimport sys\nimport time\n\n\nlogging.basicConfig(level=logging.DEBUG,\n format='%(levelname)s: [%(name)s] %(message)s')\nlogger = logging.getLogger('moonlite')\n\n\nclass ProgramStatus(object):\n \"\"\"\n A simple class to show the progress.\n \"\"\"\n def __init__(self, N, interval=1.0):\n self._N = N\n self._interval = interval\n self._last_show = time.time()\n self._start_timer = 0.0\n self._time = [0.0, 0.0, 0.0]\n self._item_N = [0, 0, 0]\n self._total_N = [N, N, N, N]\n self._label = ['Read files\\t', 'Trace\\t\\t', 'Output\\t\\t']\n self._modules = 3\n self._last_modules = 3\n self._item_id = 0\n\n def start_timing(self, item_id):\n self._start_timer = time.time()\n self._item_id = item_id\n\n def update_item(self, n):\n idx = self._item_id\n self._item_N[idx] = n\n cur_time = time.time()\n self._time[idx] += cur_time - self._start_timer\n if cur_time - self._last_show >= self._interval:\n self._last_show = cur_time\n self.update_stat(True)\n\n def update_stat(self, revert_pos):\n if revert_pos:\n for i in xrange(self._last_modules):\n sys.stdout.write('\\033[1A\\033[K')\n self._last_modules = self._modules\n for i in xrange(self._modules):\n percent = self._item_N[i] * 100.0 / self._total_N[i]\n sys.stdout.write('%s: %.6fs\\t%d/%d\\t%.2f%%\\n' % (self._label[i],\n self._time[i],\n self._item_N[i],\n self._total_N[i],\n percent))\n\n\nclass BitVector(object):\n def __init__(self):\n self._count = 0\n self._current_char = 0\n self._vector = ''\n\n def get_vector(self):\n if self._count is not 0:\n self._add_char()\n\n return self._vector\n\n def add_bit(self, bit):\n if bit % 2 is 1:\n self._current_char += 1 << (7 - self._count)\n\n self._count += 1\n\n if self._count == 8:\n self._add_char()\n\n def _add_char(self):\n self._vector += chr(self._current_char)\n self._current_char = 0\n self._count = 0\n\n def save(self, output_path):\n logger.info('Saving bit vector trace to %s', output_path)\n\n with open(output_path, 'w') as f:\n f.write(self.get_vector())\n\n\ndef generate_bit_vector(current_tuples, global_tuples):\n \"\"\"\n Generate the bit vector.\n\n Args:\n current_tuples: the tuples read from a particular file.\n global_tuples: global view of existing tuple. Required to identify the\n position of a tuple in the bitvector.\n\n Returns:\n Bitvector representation of the given tuples.\n \"\"\"\n bit_vector = BitVector()\n idx = 0\n idx_max = len(current_tuples)\n last = -1\n\n for global_tuple in global_tuples:\n if idx >= idx_max:\n bit_vector.add_bit(0)\n continue\n\n if global_tuple < current_tuples[idx]:\n bit_vector.add_bit(0)\n continue\n\n while idx < idx_max and global_tuple > current_tuples[idx]:\n if last == global_tuple:\n logger.info('%d', global_tuple)\n idx += 1\n last = global_tuple\n\n if idx < idx_max and global_tuple == current_tuples[idx]:\n bit_vector.add_bit(1)\n else:\n bit_vector.add_bit(0)\n\n return bit_vector\n\n\ndef read_afltuples(file_name):\n \"\"\"\n Gets the afl tuples result of calling afl-showmap.\n\n Args:\n file_name: file name of the result of afl-showmap.\n\n Returns:\n A list of afl tuples contained in the file\n \"\"\"\n with open(file_name, 'r') as f:\n lines = f.readlines()\n\n return [int(line.split(':')[0]) for line in lines if line]\n\n\ndef main():\n \"\"\"The main function.\"\"\"\n parser = ArgumentParser(description='Convert AFL tuples to Moonshine '\n 'bitvectors')\n parser.add_argument('-i', '--in-dir', default='.',\n help='Input directory')\n parser.add_argument('-o', '--out-dir', default='.',\n help='Output directory')\n parser.add_argument('-p', '--input-prefix', default='afltuples-',\n help='Prefix prepended to the input file. Default is '\n '`afltuples-`')\n parser.add_argument('-r', '--output-prefix', default='exemplar-',\n help='Prefix prepended to output files. Default is '\n '`exemplar-`')\n parser.add_argument('-s', '--show-progress', action='store_true',\n default=False, help='show progress')\n args = parser.parse_args()\n\n in_dir = args.in_dir\n if not os.path.isdir(in_dir):\n logger.error('The input directory %s is invalid', in_dir)\n sys.exit(1)\n in_dir = os.path.abspath(in_dir)\n\n out_dir = args.out_dir\n if not os.path.isdir(out_dir):\n logger.error('The output directory %s is invalid', out_dir)\n sys.exit(1)\n out_dir = os.path.abspath(out_dir)\n\n in_prefix = args.input_prefix\n input_regex = re.compile(r'%s(?P.*)' % in_prefix)\n out_prefix = args.output_prefix\n\n show_progress = args.show_progress\n\n tuple_files = glob.glob(os.path.join(in_dir, '%s*' % in_prefix))\n if not tuple_files:\n logger.error('No files with prefix `%s` found in %s', in_prefix,\n in_dir)\n sys.exit(1)\n\n if show_progress:\n stat = ProgramStatus(len(tuple_files), 1.0)\n f_counter = 0\n stat.update_stat(False)\n\n tuples_seen = set()\n for tuple_file in tuple_files:\n if show_progress:\n f_counter += 1\n stat.start_timing(0)\n\n afl_tuples = read_afltuples(tuple_file)\n\n if show_progress:\n stat.update_item(f_counter)\n stat.start_timing(1)\n\n tuples_seen |= set(afl_tuples)\n\n if show_progress:\n stat.update_item(f_counter)\n\n if show_progress:\n f_counter = 0\n\n for tuple_file in tuple_files:\n if show_progress:\n f_counter += 1\n stat.start_timing(2)\n\n afl_tuples = read_afltuples(tuple_file)\n input_file = input_regex.search(tuple_file).group('input')\n out_path = os.path.join(out_dir, '%s%s.bv' % (out_prefix, input_file))\n\n bv = generate_bit_vector(sorted(afl_tuples), sorted(list(tuples_seen)))\n bv.save(out_path)\n\n if show_progress:\n stat.update_item(f_counter)\n\n if show_progress:\n stat.update_stat(True)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"moonlight-project/moonbeam","sub_path":"moonlite.py","file_name":"moonlite.py","file_ext":"py","file_size_in_byte":6916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"37370026717","text":"from concurrent import futures\nfrom enum import Enum\nimport logging\nimport threading\n\nimport grpc\n\nimport radiomessages_pb2\nimport radiomessages_pb2_grpc\nfrom google.protobuf import empty_pb2\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass RadioRPC():\n \"\"\"\n Class for invoking RPCs for the radio service.\n \"\"\"\n\n def __init__(self, host):\n logger.info(\"Connecting to grpc channel\")\n self.channel = grpc.insecure_channel(host)\n self.stub = radiomessages_pb2_grpc.RadioStub(self.channel)\n self._listener_threads = {}\n\n def play(self, url=None):\n try:\n logger.debug(\"Sending play request\")\n response = self.stub.Play(radiomessages_pb2.PlayRequest(url=url))\n return RadioRPC._format_status(response)\n except grpc.RpcError as e:\n if e.code() == grpc.StatusCode.INVALID_ARGUMENT:\n raise ValueError(e.details())\n else:\n raise\n\n\n def stop(self):\n logger.debug(\"Sending stop request\")\n return RadioRPC._format_status(self.stub.Stop(empty_pb2.Empty()))\n\n\n def set_volume(self, volume):\n logger.debug(\"Setting volume\")\n response = self.stub.SetVolume(radiomessages_pb2.VolumeRequest(volume=volume))\n return RadioRPC._format_status(response)\n\n\n def get_status(self):\n logger.debug(\"Sending get status request\")\n return RadioRPC._format_status(self.stub.Status(empty_pb2.Empty()))\n\n\n def subscribe_to_updates(self, listener):\n logger.debug(\"Subscribing to updates\")\n def async_listener():\n for status in self.stub.SubscribeToUpdates(empty_pb2.Empty()):\n if status:\n listener(RadioRPC._format_status(status))\n\n t = threading.Thread(target=async_listener)\n t.start()\n self._listener_threads[listener] = t\n\n\n def unsubscribe_to_updates(self, listener):\n self.stub.UnsubscribeToUpdates(empty_pb2.Empty())\n if listener in self._listener_threads:\n self._listener_threads[listener].join()\n\n\n @staticmethod\n def _format_status(status):\n \"\"\"\n Converts a format into a generic dict representation\n \"\"\"\n return {\n 'url': status.url,\n 'state': RadioState(status.state),\n 'title': status.title,\n 'name': status.name,\n 'volume': status.volume,\n 'bitrate': status.bitrate,\n }\n\n\nclass RadioState(Enum):\n PLAYING = 0\n STOPPED = 1\n MUTED = 2\n","repo_name":"mKaloer/rpi-radio-player","sub_path":"api-server/api-server/radio_rpc.py","file_name":"radio_rpc.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"3"} +{"seq_id":"72196183123","text":"from kipet.library.TemplateBuilder import *\nfrom kipet.library.CasadiSimulator import *\nimport matplotlib.pyplot as plt\nimport casadi as ca\nimport sys\n\nif __name__ == \"__main__\":\n\n with_plots = True\n if len(sys.argv)==2:\n if int(sys.argv[1]):\n with_plots = False\n\n \n # create template model \n builder = TemplateBuilder() \n builder.add_mixture_component('A',6.7)\n builder.add_mixture_component('B',20.0)\n builder.add_mixture_component('C',0.0)\n \n builder.add_complementary_state_variable('T',290.0)\n \n builder.add_parameter('k_p',3.734e7)\n\n # define explicit system of ODEs\n def rule_odes(m,t):\n r = -m.P['k_p']*ca.exp(-15400.0/(1.987*m.X[t,'T']))*m.Z[t,'A']*m.Z[t,'B']\n T1 = 45650.0*(-r*0.01)/28.0\n #T2 = ca.if_else(m.X[t,'T']>328.0,0.0,2.0)\n T2 = 1+(328.0-m.X[t,'T'])/((328.0-m.X[t,'T'])**2+1e-5**2)**0.5\n exprs = dict()\n exprs['A'] = r\n exprs['B'] = r\n exprs['C'] = -r\n exprs['T'] = T1+T2\n\n return exprs\n \n builder.set_odes_rule(rule_odes)\n\n # create an instance of a casadi model template\n casadi_model = builder.create_casadi_model(0.0,20.0) \n \n # create instance of simulator\n sim = CasadiSimulator(casadi_model)\n # defines the discrete points wanted in the concentration profile\n sim.apply_discretization('integrator',nfe=200)\n # simulate\n results_casadi = sim.run_sim(\"cvodes\")\n\n # display concentration results\n if with_plots:\n results_casadi.Z.plot.line(legend=True)\n plt.xlabel(\"time (s)\")\n plt.ylabel(\"Concentration (mol/L)\")\n plt.title(\"Concentration Profile\")\n\n results_casadi.X.plot.line(legend=True)\n plt.xlabel(\"time (s)\")\n plt.ylabel(\"Temperature (K)\")\n plt.title(\"Temperature Profile\")\n \n plt.show()\n","repo_name":"tkrumpol/KIPET","sub_path":"kipet/validation/test_problems/complementary_states/casadi/ode_conditional_sim.py","file_name":"ode_conditional_sim.py","file_ext":"py","file_size_in_byte":1867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"40315331853","text":"import networkx as nx\n\nfrom community import community_louvain\n\n\n\ndef GetNxGraph( bacterias, adjacency_matrix ):\n stages = list( adjacency_matrix.keys() )\n graph = nx.Graph()\n for b1 in bacterias:\n added = False\n for b2 in bacterias:\n if b1 >= b2 :\n continue\n if (b1,b2) in adjacency_matrix:\n graph.add_edge( b1, b2, weight=adjacency_matrix[b1,b2] )\n added = True\n if not added:\n graph.add_node(b1)\n return graph\n\ndef Step2_1( bacterias, stageToAdjacency_matrix):\n stages = list( stageToAdjacency_matrix.keys() )\n stageToNxGraph = dict()\n for s in stages:\n stageToNxGraph[s] = GetNxGraph( bacterias, stageToAdjacency_matrix[s])\n stageToCluster = dict()\n for s in stages:\n stageToCluster[s] = community_louvain.best_partition( stageToNxGraph[s], random_state = 0 )\n return stageToCluster\n\n\nimport union_find \ndef Step2_2( bacterias, sup_category, abundance_mean, stageToBactToCluster):\n s1,s2 = tuple( stageToBactToCluster.keys() )\n uf = union_find.UnionFind(bacterias)\n for b1 in bacterias:\n for b2 in bacterias:\n if b1 >= b2:\n continue\n if uf.isSame( b1, b2 ):\n continue\n term1 = stageToBactToCluster[s1][b1] == stageToBactToCluster[s1][b2] and stageToBactToCluster[s2][b1] == stageToBactToCluster[s2][b2]\n term2 = sup_category[b1] == sup_category[b2]\n if term1 and term2:\n uf.unite( b1, b2 )\n\n parentToMost = dict()\n for b in bacterias:\n parent = uf.find(b)\n if parent not in parentToMost.keys():\n parentToMost[ parent ] = b\n else:\n parentToMost[ parent ] = max( parentToMost[parent], b, key = lambda x: abundance_mean[x] )\n\n contract_set_list = dict()\n for b in bacterias:\n most = parentToMost[uf.find(b)]\n if most not in contract_set_list.keys():\n contract_set_list[most] = []\n contract_set_list[most].append(b)\n return contract_set_list\n\n\ndef Step2_3( contract_set_list, stageToAdjacency_matrix ):\n bacteria_contracted = contract_set_list.keys()\n adjacency_matrix_contracted = dict()\n for s in stageToAdjacency_matrix.keys():\n adjacency_matrix_contracted[s] = dict()\n for b1 in bacteria_contracted:\n for b2 in bacteria_contracted:\n if b1 >= b2:\n continue\n contract_set1 = contract_set_list[ b1 ]\n contract_set2 = contract_set_list[ b2 ]\n weight_sum = 0. \n cnt = 0\n for v1 in contract_set1:\n for v2 in contract_set2:\n if (v1,v2) not in stageToAdjacency_matrix[s]:\n continue\n weight_sum += stageToAdjacency_matrix[s][v1,v2]\n cnt += 1\n if cnt == 0:\n continue\n adjacency_matrix_contracted[s][ b1, b2 ] = weight_sum / cnt\n return bacteria_contracted, adjacency_matrix_contracted\n ","repo_name":"DiscreteAlgorithms/QNetDiff","sub_path":"step2.py","file_name":"step2.py","file_ext":"py","file_size_in_byte":3147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"3"} +{"seq_id":"17434931674","text":"\"\"\"\nUsage:\n 4c align [--out=NAME] [--qual=QUAL]
| \n | \n \n Preview Image is unavailable! \n What now?\n
| \n
| \n | \n \n No Ibl Set to inspect! \n Please add some Ibl Set to the Database or select a non empty Collection!\n | \n
{0}
\nAuthor: {1}
\n Location: {2}
\n Shot Date: {3}
\n Comment: {4}